diff --git a/grpc/src/compiler/swift_generator.cc b/grpc/src/compiler/swift_generator.cc index bb731d54f..95e8858cf 100644 --- a/grpc/src/compiler/swift_generator.cc +++ b/grpc/src/compiler/swift_generator.cc @@ -100,7 +100,7 @@ void GenerateClientProtocol(const grpc_generator::Service *service, vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name()); vars["MethodName"] = method->name(); vars["isNil"] = ""; - printer->Print("\t"); + printer->Print(" "); auto func = GenerateClientFuncName(method.get()); printer->Print(vars, func.c_str()); printer->Print("\n"); @@ -115,15 +115,15 @@ void GenerateClientClass(const grpc_generator::Service *service, printer->Print(vars, "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: GRPCClient, " "$ServiceQualifiedName$Service {\n"); - printer->Print(vars, "\t$ACCESS$ let channel: GRPCChannel\n"); - printer->Print(vars, "\t$ACCESS$ var defaultCallOptions: CallOptions\n"); + printer->Print(vars, " $ACCESS$ let channel: GRPCChannel\n"); + printer->Print(vars, " $ACCESS$ var defaultCallOptions: CallOptions\n"); printer->Print("\n"); printer->Print(vars, - "\t$ACCESS$ init(channel: GRPCChannel, " + " $ACCESS$ init(channel: GRPCChannel, " "defaultCallOptions: CallOptions = CallOptions()) {\n"); - printer->Print("\t\tself.channel = channel\n"); - printer->Print("\t\tself.defaultCallOptions = defaultCallOptions\n"); - printer->Print("\t}"); + printer->Print(" self.channel = channel\n"); + printer->Print(" self.defaultCallOptions = defaultCallOptions\n"); + printer->Print(" }"); printer->Print("\n"); vars["GenAccess"] = service->is_internal() ? "internal" : "public"; for (auto it = 0; it < service->method_count(); it++) { @@ -132,14 +132,14 @@ void GenerateClientClass(const grpc_generator::Service *service, vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name()); vars["MethodName"] = method->name(); vars["isNil"] = " = nil"; - printer->Print("\n\t"); + printer->Print("\n "); auto func = GenerateClientFuncName(method.get()); printer->Print(vars, func.c_str()); printer->Print(" {\n"); auto body = GenerateClientFuncBody(method.get()); - printer->Print("\t\t"); + printer->Print(" "); printer->Print(vars, body.c_str()); - printer->Print("\n\t}\n"); + printer->Print("\n }\n"); } printer->Print("}\n"); } @@ -168,44 +168,44 @@ grpc::string GenerateServerFuncName(const grpc_generator::Method *method) { } grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) { - grpc::string start = "\t\tcase \"$MethodName$\":\n\t\t"; + grpc::string start = " case \"$MethodName$\":\n "; if (method->NoStreaming()) { return start + "return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { " "context in" - "\n\t\t\t" + "\n " "return { request in" - "\n\t\t\t\t" + "\n " "self.$MethodName$(request, context: context)" - "\n\t\t\t}" - "\n\t\t}"; + "\n }" + "\n }"; } if (method->ClientStreaming()) { return start + "return CallHandlerFactory.makeClientStreaming(callHandlerContext: " "callHandlerContext) { context in" - "\n\t\t\t" + "\n " "self.$MethodName$(context: context)" - "\n\t\t}"; + "\n }"; } if (method->ServerStreaming()) { return start + "return CallHandlerFactory.makeServerStreaming(callHandlerContext: " "callHandlerContext) { context in" - "\n\t\t\t" + "\n " "return { request in" - "\n\t\t\t\t" + "\n " "self.$MethodName$(request: request, context: context)" - "\n\t\t\t}" - "\n\t\t}"; + "\n }" + "\n }"; } if (method->BidiStreaming()) { return start + "return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: " "callHandlerContext) { context in" - "\n\t\t\t" + "\n " "self.$MethodName$(context: context)" - "\n\t\t}"; + "\n }"; } return ""; } @@ -221,7 +221,7 @@ void GenerateServerProtocol(const grpc_generator::Service *service, vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name()); vars["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name()); vars["MethodName"] = method->name(); - printer->Print("\t"); + printer->Print(" "); auto func = GenerateServerFuncName(method.get()); printer->Print(vars, func.c_str()); printer->Print("\n"); @@ -231,13 +231,13 @@ void GenerateServerProtocol(const grpc_generator::Service *service, printer->Print(vars, "$ACCESS$ extension $ServiceQualifiedName$Provider {\n"); printer->Print("\n"); printer->Print(vars, - "\tvar serviceName: Substring { return " + " var serviceName: Substring { return " "\"$PATH$$ServiceName$\" }\n"); printer->Print("\n"); printer->Print( - "\tfunc handleMethod(_ methodName: Substring, callHandlerContext: " + " func handleMethod(_ methodName: Substring, callHandlerContext: " "CallHandlerContext) -> GRPCCallHandler? {\n"); - printer->Print("\t\tswitch methodName {\n"); + printer->Print(" switch methodName {\n"); for (auto it = 0; it < service->method_count(); it++) { auto method = service->method(it); vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name()); @@ -247,10 +247,10 @@ void GenerateServerProtocol(const grpc_generator::Service *service, printer->Print(vars, body.c_str()); printer->Print("\n"); } - printer->Print("\t\tdefault: return nil;\n"); - printer->Print("\t\t}\n"); - printer->Print("\t}\n\n"); - printer->Print("}\n\n"); + printer->Print(" default: return nil;\n"); + printer->Print(" }\n"); + printer->Print(" }\n\n"); + printer->Print("}"); } grpc::string Generate(grpc_generator::File *file, @@ -281,6 +281,10 @@ grpc::string GenerateHeader() { code += "/// in case of an issue please open github issue, though it would be " "maintained\n"; + code += "\n"; + code += "// swiftlint:disable all\n"; + code += "// swiftformat:disable all\n"; + code += "\n"; code += "import Foundation\n"; code += "import GRPC\n"; code += "import NIO\n"; @@ -292,19 +296,19 @@ grpc::string GenerateHeader() { "{}\n"; code += "public extension GRPCFlatBufPayload {\n"; - code += " init(serializedByteBuffer: inout NIO.ByteBuffer) throws {\n"; + code += " init(serializedByteBuffer: inout NIO.ByteBuffer) throws {\n"; code += - " self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: " + " self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: " "serializedByteBuffer.readableBytesView, count: " "serializedByteBuffer.readableBytes))\n"; - code += " }\n"; + code += " }\n"; - code += " func serialize(into buffer: inout NIO.ByteBuffer) throws {\n"; + code += " func serialize(into buffer: inout NIO.ByteBuffer) throws {\n"; code += - " let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: " + " let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: " "Int(self.size))\n"; - code += " buffer.writeBytes(buf)\n"; - code += " }\n"; + code += " buffer.writeBytes(buf)\n"; + code += " }\n"; code += "}\n"; code += "extension Message: GRPCFlatBufPayload {}\n"; return code; diff --git a/samples/sample_binary.swift b/samples/sample_binary.swift index 832eb3d55..46ab99be1 100644 --- a/samples/sample_binary.swift +++ b/samples/sample_binary.swift @@ -1,4 +1,19 @@ - // THIS IS JUST TO SHOW THE CODE, PLEASE DO IMPORT FLATBUFFERS WITH SPM.. +/* + * 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 FlatBuffers typealias Monster = MyGame.Sample.Monster @@ -7,61 +22,62 @@ typealias Color = MyGame.Sample.Color typealias Vec3 = MyGame.Sample.Vec3 func main() { - let expectedDMG: [Int16] = [3, 5] - let expectedNames = ["Sword", "Axe"] + let expectedDMG: [Int16] = [3, 5] + let expectedNames = ["Sword", "Axe"] - var builder = FlatBufferBuilder(initialSize: 1024) - let weapon1Name = builder.create(string: expectedNames[0]) - let weapon2Name = builder.create(string: expectedNames[1]) - - let weapon1Start = Weapon.startWeapon(&builder) - Weapon.add(name: weapon1Name, &builder) - Weapon.add(damage: expectedDMG[0], &builder) - let sword = Weapon.endWeapon(&builder, start: weapon1Start) - let weapon2Start = Weapon.startWeapon(&builder) - Weapon.add(name: weapon2Name, &builder) - Weapon.add(damage: expectedDMG[1], &builder) - let axe = Weapon.endWeapon(&builder, start: weapon2Start) - - let name = builder.create(string: "Orc") - let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - let inventoryOffset = builder.createVector(inventory) + var builder = FlatBufferBuilder(initialSize: 1024) + let weapon1Name = builder.create(string: expectedNames[0]) + let weapon2Name = builder.create(string: expectedNames[1]) - let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) - let pos = MyGame.Sample.createVec3(x: 1, y: 2, z: 3) + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: expectedDMG[0], &builder) + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: expectedDMG[1], &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) - let orc = Monster.createMonster(&builder, - structOfPos: pos, - hp: 300, - offsetOfName: name, - vectorOfInventory: inventoryOffset, - color: .red, - vectorOfWeapons: weaponsOffset, - equippedType: .weapon, - offsetOfEquipped: axe) - builder.finish(offset: orc) - - let buf = builder.sizedByteArray - let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf)) + let name = builder.create(string: "Orc") + let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + let inventoryOffset = builder.createVector(inventory) - assert(monster.mana == 150) - assert(monster.hp == 300) - assert(monster.name == "Orc") - assert(monster.color == MyGame.Sample.Color.red) - assert(monster.pos != nil) - for i in 0..=5.0) - /// Constructor that creates a Flatbuffer object from a ContiguousBytes - /// - Parameters: - /// - contiguousBytes: Binary stripe to use as the buffer - /// - count: amount of readable bytes - public init( - contiguousBytes: Bytes, - count: Int - ) { - _storage = Storage(count: count, alignment: alignment) - _writerSize = _storage.capacity - 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 - /// - Parameter capacity: The size of the given memory region - public init(assumingMemoryBound memory: UnsafeMutableRawPointer, capacity: Int) { - _storage = Storage(memory: memory, capacity: capacity, unowned: true) - _writerSize = capacity + deinit { + if !unowned { + memory.deallocate() + } } - /// Creates a copy of the buffer that's being built by calling sizedBuffer - /// - Parameters: - /// - memory: Current memory of the buffer - /// - count: count of bytes - internal init(memory: UnsafeMutableRawPointer, count: Int) { - _storage = Storage(count: count, alignment: alignment) - _storage.copy(from: memory, count: count) - _writerSize = _storage.capacity + 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) } - /// 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 - internal init(memory: UnsafeMutableRawPointer, count: Int, removing removeBytes: Int) { - _storage = Storage(count: count, alignment: alignment) - _storage.copy(from: memory, count: count) - _writerSize = removeBytes + func initialize(for size: Int) { + assert( + !unowned, + "initalize should NOT be called on a buffer that is built by assumingMemoryBound") + memset(memory, 0, size) } - /// Fills the buffer with padding by adding to the writersize - /// - Parameter padding: Amount of padding between two to be serialized objects - @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 - @usableFromInline mutating func push(elements: [T]) { - let size = elements.count &* MemoryLayout.size - ensureSpace(size: size) - elements.reversed().forEach { (s) in - push(value: s, len: MemoryLayout.size(ofValue: s)) - } - } + /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer + /// - Parameter size: Size of the current object + @usableFromInline + internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) { + let currentWritingIndex = capacity &- writerSize + while capacity <= writerSize &+ size { + capacity = capacity << 1 + } - /// A custom type of structs that are padded according to the flatbuffer padding, - /// - Parameters: - /// - value: Pointer to the object in memory - /// - size: Size of Value being written to the buffer - @available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") - @usableFromInline mutating func push(struct value: UnsafeMutableRawPointer, size: Int) { - ensureSpace(size: size) - memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size) - defer { value.deallocate() } - _writerSize = _writerSize &+ size - } - - /// Prepares the buffer to receive a struct of certian size. - /// The alignment of the memory is already handled since we already called preAlign - /// - Parameter size: size of the struct - @usableFromInline mutating func prepareBufferToReceiveStruct(of size: Int) { - ensureSpace(size: size) - _writerSize = _writerSize &+ size - } - - /// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex` - /// and writes front to back into the buffer, respecting the padding & the alignment - /// - Parameters: - /// - value: value of type Scalar - /// - position: position relative to the `writerIndex` - /// - len: length of the value in terms of bytes - @usableFromInline mutating func reversePush(value: T, position: Int, len: Int) { - var v = value - memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len) - } + /// solution take from Apple-NIO + capacity = capacity.convertToPowerofTwo - /// 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 - @usableFromInline mutating func push(value: T, len: Int) { - ensureSpace(size: len) - var v = value - memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len) - _writerSize = _writerSize &+ len + 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 } + } - /// 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 - @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) - } - } - } + @usableFromInline var _storage: Storage - /// Writes a string to Bytebuffer using UTF8View - /// - Parameters: - /// - bytes: Pointer to the view - /// - len: Size of string - @usableFromInline mutating internal func push(bytes: UnsafeBufferPointer, len: Int) -> Bool { - memcpy(_storage.memory.advanced(by: writerIndex &- len), UnsafeRawPointer(bytes.baseAddress!), len) - _writerSize = _writerSize &+ len - return true - } + /// The size of the elements written to the buffer + their paddings + private var _writerSize: Int = 0 + /// Aliginment of the current memory being written to the buffer + internal 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 + internal var writerIndex: Int { _storage.capacity &- _writerSize } - /// 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 - 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") - _storage.memory.storeBytes(of: value, toByteOffset: index, as: T.self) - } + /// 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 } - /// 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 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 mutating internal 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 - mutating public func clearSize() { - _writerSize = 0 + /// Constructor that creates a Flatbuffer object from a UInt8 + /// - Parameter bytes: Array of UInt8 + public init(bytes: [UInt8]) { + var b = bytes + _storage = Storage(count: bytes.count, alignment: alignment) + _writerSize = _storage.capacity + b.withUnsafeMutableBytes { bufferPointer in + self._storage.copy(from: bufferPointer.baseAddress!, count: bytes.count) } + } - /// Clears the current instance of the buffer, replacing it with new memory - 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 - public func read(def: T.Type, position: Int) -> T { - assert(position + MemoryLayout.size <= _storage.capacity, "Reading out of bounds is illegal") - return _storage.memory.advanced(by: position).load(as: T.self) + /// Constructor that creates a Flatbuffer from the Swift Data type object + /// - Parameter data: Swift data Object + public init(data: Data) { + var b = data + _storage = Storage(count: data.count, alignment: alignment) + _writerSize = _storage.capacity + b.withUnsafeMutableBytes { bufferPointer in + self._storage.copy(from: bufferPointer.baseAddress!, count: data.count) } + } - /// 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 - public func readSlice(index: Int32, - count: Int32) -> [T] { - let _index = Int(index) - let _count = Int(count) - 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) - } + /// Constructor that creates a Flatbuffer instance with a size + /// - Parameter size: Length of the buffer + init(initialSize size: Int) { + let size = size.convertToPowerofTwo + _storage = Storage(count: size, alignment: alignment) + _storage.initialize(for: size) + } - /// 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 - public func readString(at index: Int32, - count: Int32, - type: String.Encoding = .utf8) -> String? { - let _index = Int(index) - let _count = Int(count) - 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) + #if swift(>=5.0) + /// Constructor that creates a Flatbuffer object from a ContiguousBytes + /// - Parameters: + /// - contiguousBytes: Binary stripe to use as the buffer + /// - count: amount of readable bytes + public init( + contiguousBytes: Bytes, + count: Int) + { + _storage = Storage(count: count, alignment: alignment) + _writerSize = _storage.capacity + contiguousBytes.withUnsafeBytes { buf in + _storage.copy(from: buf.baseAddress!, count: buf.count) } + } + #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 - 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) + /// Constructor that creates a Flatbuffer from unsafe memory region without copying + /// - Parameter assumingMemoryBound: The unsafe memory region + /// - Parameter capacity: The size of the given memory region + public init(assumingMemoryBound memory: UnsafeMutableRawPointer, capacity: Int) { + _storage = Storage(memory: memory, capacity: capacity, unowned: true) + _writerSize = capacity + } + + /// Creates a copy of the buffer that's being built by calling sizedBuffer + /// - Parameters: + /// - memory: Current memory of the buffer + /// - count: count of bytes + internal init(memory: UnsafeMutableRawPointer, count: Int) { + _storage = Storage(count: count, alignment: alignment) + _storage.copy(from: memory, count: count) + _writerSize = _storage.capacity + } + + /// 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 + internal init(memory: UnsafeMutableRawPointer, count: Int, removing removeBytes: Int) { + _storage = Storage(count: count, alignment: alignment) + _storage.copy(from: memory, count: count) + _writerSize = removeBytes + } + + /// Fills the buffer with padding by adding to the writersize + /// - Parameter padding: Amount of padding between two to be serialized objects + @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 + @usableFromInline + mutating func push(elements: [T]) { + let size = elements.count &* MemoryLayout.size + ensureSpace(size: size) + elements.reversed().forEach { s in + push(value: s, len: MemoryLayout.size(ofValue: s)) } + } + + /// A custom type of structs that are padded according to the flatbuffer padding, + /// - Parameters: + /// - value: Pointer to the object in memory + /// - size: Size of Value being written to the buffer + @available( + *, + deprecated, + message: "0.9.0 will be removing the following method. Regenerate the code") + @usableFromInline + mutating func push(struct value: UnsafeMutableRawPointer, size: Int) { + ensureSpace(size: size) + memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size) + defer { value.deallocate() } + _writerSize = _writerSize &+ size + } + + /// Prepares the buffer to receive a struct of certian size. + /// The alignment of the memory is already handled since we already called preAlign + /// - Parameter size: size of the struct + @usableFromInline + mutating func prepareBufferToReceiveStruct(of size: Int) { + ensureSpace(size: size) + _writerSize = _writerSize &+ size + } + + /// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex` + /// and writes front to back into the buffer, respecting the padding & the alignment + /// - Parameters: + /// - value: value of type Scalar + /// - position: position relative to the `writerIndex` + /// - len: length of the value in terms of bytes + @usableFromInline + mutating func reversePush(value: T, position: Int, len: Int) { + var v = value + memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len) + } + + /// 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 + @usableFromInline + mutating func push(value: T, len: Int) { + ensureSpace(size: len) + var v = value + memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, 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 + @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 + mutating internal func push( + bytes: UnsafeBufferPointer, + len: Int) -> Bool + { + memcpy( + _storage.memory.advanced(by: writerIndex &- len), + UnsafeRawPointer(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 + 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") + _storage.memory.storeBytes(of: value, toByteOffset: index, as: T.self) + } + + /// 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 + 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 + mutating internal 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 + mutating public func clearSize() { + _writerSize = 0 + } + + /// Clears the current instance of the buffer, replacing it with new memory + 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 + public func read(def: T.Type, position: Int) -> T { + assert( + position + MemoryLayout.size <= _storage.capacity, + "Reading out of bounds is illegal") + 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 + public func readSlice( + index: Int32, + count: Int32) -> [T] + { + let _index = Int(index) + let _count = Int(count) + 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) + } + + /// 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 + public func readString( + at index: Int32, + count: Int32, + type: String.Encoding = .utf8) -> String? + { + let _index = Int(index) + let _count = Int(count) + 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) + } + + /// Creates a new Flatbuffer object that's duplicated from the current one + /// - Parameter removeBytes: the amount of bytes to remove from the current Size + 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) + } } extension ByteBuffer: CustomDebugStringConvertible { - public var debugDescription: String { - """ - buffer located at: \(_storage.memory), with capacity of \(_storage.capacity) - { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) } - """ - } + public var debugDescription: String { + """ + buffer located at: \(_storage.memory), with capacity of \(_storage.capacity) + { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) } + """ + } } diff --git a/swift/Sources/FlatBuffers/Constants.swift b/swift/Sources/FlatBuffers/Constants.swift index 2b55250d3..ac541d9cc 100644 --- a/swift/Sources/FlatBuffers/Constants.swift +++ b/swift/Sources/FlatBuffers/Constants.swift @@ -1,3 +1,19 @@ +/* + * 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. + */ + #if os(Linux) import CoreFoundation #else @@ -20,77 +36,77 @@ public let FlatBufferMaxSize = UInt32.max << ((MemoryLayout.size * 8 - /// /// Scalar is used to confirm 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 } + associatedtype NumericValue + var convertedEndian: NumericValue { get } } 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 { - return self as! Self.NumericValue - } + /// 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 { - public typealias NumericValue = UInt64 - - public var convertedEndian: UInt64 { - return self.bitPattern.littleEndian - } + public typealias NumericValue = UInt64 + + public var convertedEndian: UInt64 { + bitPattern.littleEndian + } } extension Float32: Scalar { - public typealias NumericValue = UInt32 - - public var convertedEndian: UInt32 { - return self.bitPattern.littleEndian - } + public typealias NumericValue = UInt32 + + public var convertedEndian: UInt32 { + bitPattern.littleEndian + } } extension Bool: Scalar { - public var convertedEndian: UInt8 { - return self == true ? 1 : 0 - } - - public typealias NumericValue = UInt8 + public var convertedEndian: UInt8 { + self == true ? 1 : 0 + } + + public typealias NumericValue = UInt8 } extension Int: Scalar { - public typealias NumericValue = Int + public typealias NumericValue = Int } extension Int8: Scalar { - public typealias NumericValue = Int8 + public typealias NumericValue = Int8 } extension Int16: Scalar { - public typealias NumericValue = Int16 + public typealias NumericValue = Int16 } extension Int32: Scalar { - public typealias NumericValue = Int32 + public typealias NumericValue = Int32 } extension Int64: Scalar { - public typealias NumericValue = Int64 + public typealias NumericValue = Int64 } extension UInt8: Scalar { - public typealias NumericValue = UInt8 + public typealias NumericValue = UInt8 } extension UInt16: Scalar { - public typealias NumericValue = UInt16 + public typealias NumericValue = UInt16 } extension UInt32: Scalar { - public typealias NumericValue = UInt32 + public typealias NumericValue = UInt32 } extension UInt64: Scalar { - public typealias NumericValue = UInt64 + public typealias NumericValue = UInt64 } public func FlatBuffersVersion_1_12_0() {} diff --git a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift index cfdb20cec..71fcab002 100644 --- a/swift/Sources/FlatBuffers/FlatBufferBuilder.swift +++ b/swift/Sources/FlatBuffers/FlatBufferBuilder.swift @@ -1,602 +1,645 @@ +/* + * 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 Foundation 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() - - /// Reference Vtables that were already written to the buffer - private var _vtables: [UOffset] = [] - /// Flatbuffer data will be written into - private var _bb: ByteBuffer - /// 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 - } + + /// 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() + + /// Reference Vtables that were already written to the buffer + private var _vtables: [UOffset] = [] + /// Flatbuffer data will be written into + private var _bb: ByteBuffer + /// 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 { return _bb.size } - /// Data representation of the buffer - 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) + } + + /// Gives a read access to the buffer's size + public var size: UOffset { _bb.size } + /// Data representation of the buffer + 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) + } + /// Get's the fully sized buffer stored in memory + public var fullSizedByteArray: [UInt8] { + let ptr = UnsafeBufferPointer( + start: _bb.memory.assumingMemoryBound(to: UInt8.self), + count: _bb.capacity) + return Array(ptr) + } + /// Returns the written size of the buffer + public var sizedByteArray: [UInt8] { + assert(finished, "Data shouldn't be called before finish()") + let cp = _bb.capacity &- _bb.writerIndex + let start = _bb.memory.advanced(by: _bb.writerIndex) + .bindMemory(to: UInt8.self, capacity: cp) + + let ptr = UnsafeBufferPointer(start: start, count: cp) + return Array(ptr) + } + /// Returns the buffer + public var buffer: ByteBuffer { _bb } + + /// Returns A sized Buffer from the readable bytes + 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 + 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") } - /// Get's the fully sized buffer stored in memory - public var fullSizedByteArray: [UInt8] { - let ptr = UnsafeBufferPointer(start: _bb.memory.assumingMemoryBound(to: UInt8.self), - count: _bb.capacity) - return Array(ptr) + serializeDefaults = force + _bb = ByteBuffer(initialSize: Int(initialSize)) + } + + /// Clears the buffer and the builder from it's data + mutating public func clear() { + _minAlignment = 0 + isNested = false + stringOffsetMap = [:] + _vtables = [] + _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 + mutating public func require(table: Offset, fields: [Int32]) { + for field in fields { + 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(field)) != 0 + assert(isOkay, "Flatbuffers requires the following field") } - /// Returns the written size of the buffer - public var sizedByteArray: [UInt8] { - assert(finished, "Data shouldn't be called before finish()") - let cp = _bb.capacity &- _bb.writerIndex - let start = _bb.memory.advanced(by: _bb.writerIndex) - .bindMemory(to: UInt8.self, capacity: cp) - - let ptr = UnsafeBufferPointer(start: start, count: cp) - return Array(ptr) - } - /// Returns the buffer - public var buffer: ByteBuffer { return _bb } - - /// Returns A sized Buffer from the readable bytes - 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 - 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 buffer and the builder from it's data - mutating public func clear() { - _minAlignment = 0 - isNested = false - stringOffsetMap = [:] - _vtables = [] - _vtableStorage.clear() - _bb.clear() + } + + /// 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 + 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 + 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 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 + /// - Parameter numOfFields: Number of elements to be written to the buffer + mutating public func startTable(with numOfFields: Int) -> UOffset { + notNested() + isNested = true + _vtableStorage.start(count: numOfFields) + return _bb.size + } + + /// Endtable will let the builder 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 vtable into the buffer. + /// it will fatalError in case the object is called without starttable, 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) } - // 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 - mutating public func require(table: Offset, fields: [Int32]) { - for field in fields { - 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(field)) != 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 - 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 - 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 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 - /// - Parameter numOfFields: Number of elements to be written to the buffer - mutating public func startTable(with numOfFields: Int) -> UOffset { - notNested() - isNested = true - _vtableStorage.start(count: numOfFields) - return _bb.size - } - - /// Endtable will let the builder 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 vtable into the buffer. - /// it will fatalError in case the object is called without starttable, 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) + _vtableStorage.clear() + let vt_use = _bb.size - for table in _vtables { - let position = _bb.capacity &- Int(table) - 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(table) - 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 - @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 - @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 - @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 - @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 - @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 - @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 - @usableFromInline mutating internal func track(offset: UOffset, at position: VOffset) { - _vtableStorage.add(loc: FieldLoc(offset: offset, position: position)) + var isAlreadyAdded: Int? + + let vt2 = _bb.memory.advanced(by: _bb.writerIndex) + let len2 = vt2.load(fromByteOffset: 0, as: Int16.self) + + for table in _vtables { + let position = _bb.capacity &- Int(table) + 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(table) + break } - // MARK: - Vectors - - /// Starts a vector of length and Element size - mutating public func startVector(_ len: Int, elementSize: Int) { - notNested() - isNested = true - preAlign(len: len &* elementSize, type: UOffset.self) - preAlign(len: len &* elementSize, alignment: elementSize) - } - - /// Ends the vector of at length - /// - /// The current function will fatalError if startVector is called before serializing the vector - /// - Parameter len: Length of the buffer - mutating public func endVector(len: Int) -> UOffset { - assert(isNested, "Calling endVector without calling startVector") - isNested = false - return push(element: Int32(len)) - } - - /// Creates a vector of type Scalar in the buffer - /// - Parameter elements: elements to be written into the buffer - /// - returns: Offset of the vector - mutating public func createVector(_ elements: [T]) -> Offset { - return createVector(elements, size: elements.count) - } - - /// Creates a vector of type Scalar in the buffer - /// - Parameter elements: Elements to be written into the buffer - /// - Parameter size: Count of elements - /// - returns: Offset of the vector - mutating public func createVector(_ elements: [T], size: Int) -> Offset { - let size = size - startVector(size, elementSize: MemoryLayout.size) - _bb.push(elements: elements) - return Offset(offset: endVector(len: size)) - } - - /// Creates a vector of type Enums in the buffer - /// - Parameter elements: elements to be written into the buffer - /// - returns: Offset of the vector - mutating public func createVector(_ elements: [T]) -> Offset { - return createVector(elements, size: elements.count) - } - - /// Creates a vector of type Enums in the buffer - /// - Parameter elements: Elements to be written into the buffer - /// - Parameter size: Count of elements - /// - returns: Offset of the vector - mutating public func createVector(_ elements: [T], size: Int) -> Offset { - let size = size - startVector(size, elementSize: T.byteSize) - for e in elements.reversed() { - _bb.push(value: e.value, len: T.byteSize) - } - return Offset(offset: endVector(len: size)) - } - - /// Creates a vector of type Offsets in the buffer - /// - Parameter offsets:Array of offsets of type T - /// - returns: Offset of the vector - mutating public func createVector(ofOffsets offsets: [Offset]) -> Offset { - createVector(ofOffsets: offsets, len: offsets.count) - } - - /// Creates a vector of type Offsets in the buffer - /// - Parameter elements: Array of offsets of type T - /// - Parameter size: Count of elements - /// - returns: Offset of the vector - mutating public func createVector(ofOffsets offsets: [Offset], len: Int) -> Offset { - startVector(len, elementSize: MemoryLayout>.size) - for o in offsets.reversed() { - push(element: o) - } - return Offset(offset: endVector(len: len)) - } - - /// Creates a vector of Strings - /// - Parameter str: a vector of strings that will be written into the buffer - /// - returns: Offset of the vector - mutating public func createVector(ofStrings str: [String]) -> Offset { - var offsets: [Offset] = [] - for s in str { - offsets.append(create(string: s)) - } - return createVector(ofOffsets: offsets) - } - - /// Creates a vector of Flatbuffer structs. - /// - /// The function takes a Type to know what size it is, and alignment - /// - Parameters: - /// - structs: An array of UnsafeMutableRawPointer - /// - type: Type of the struct being written - /// - returns: Offset of the vector - @available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") - mutating public func createVector(structs: [UnsafeMutableRawPointer], - type: T.Type) -> Offset { - startVector(structs.count &* T.size, elementSize: T.alignment) - for i in structs.reversed() { - create(struct: i, type: T.self) - } - return Offset(offset: endVector(len: structs.count)) - } - - /// Starts a vector of struct that considers the size and alignment of the struct - /// - Parameters: - /// - count: number of elements to be written - /// - size: size of struct - /// - alignment: alignment of the struct - mutating public func startVectorOfStructs(count: Int, size: Int, alignment: Int) { - startVector(count &* size, elementSize: alignment) - } - - /// Ends the vector of structs and writtens the current offset - /// - Parameter count: number of written elements - /// - Returns: Offset of type UOffset - mutating public func endVectorOfStructs(count: Int) -> Offset { - return Offset(offset: endVector(len: count)) + 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: - Inserting Structs - - /// Writes a Flatbuffer struct into the buffer - /// - Parameters: - /// - s: Flatbuffer struct - /// - type: Type of the element to be serialized - /// - returns: Offset of the Object - @available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") - @discardableResult - mutating public func create(struct s: UnsafeMutableRawPointer, - type: T.Type) -> Offset { - let size = T.size - preAlign(len: size, alignment: T.alignment) - _bb.push(struct: s, size: size) - return Offset(offset: _bb.size) + // MARK: - Builds Buffer + + /// asserts to see if the object is not nested + @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 + @usableFromInline + mutating internal func minAlignment(size: Int) { + if size > _minAlignment { + _minAlignment = size } - - /// prepares the ByteBuffer to receive a struct of size and alignment - /// - Parameters: - /// - size: size of written struct - /// - alignment: alignment of written struct - mutating public func createStructOf(size: Int, alignment: Int) { - preAlign(len: size, alignment: alignment) - _bb.prepareBufferToReceiveStruct(of: 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 + @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 + @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 + @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 + @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 + @usableFromInline + mutating internal func track(offset: UOffset, at position: VOffset) { + _vtableStorage.add(loc: FieldLoc(offset: offset, position: position)) + } + + // MARK: - Vectors + + /// Starts a vector of length and Element size + mutating public func startVector(_ len: Int, elementSize: Int) { + notNested() + isNested = true + preAlign(len: len &* elementSize, type: UOffset.self) + preAlign(len: len &* elementSize, alignment: elementSize) + } + + /// Ends the vector of at length + /// + /// The current function will fatalError if startVector is called before serializing the vector + /// - Parameter len: Length of the buffer + mutating public func endVector(len: Int) -> UOffset { + assert(isNested, "Calling endVector without calling startVector") + isNested = false + return push(element: Int32(len)) + } + + /// Creates a vector of type Scalar in the buffer + /// - Parameter elements: elements to be written into the buffer + /// - returns: Offset of the vector + mutating public func createVector(_ elements: [T]) -> Offset { + createVector(elements, size: elements.count) + } + + /// Creates a vector of type Scalar in the buffer + /// - Parameter elements: Elements to be written into the buffer + /// - Parameter size: Count of elements + /// - returns: Offset of the vector + mutating public func createVector(_ elements: [T], size: Int) -> Offset { + let size = size + startVector(size, elementSize: MemoryLayout.size) + _bb.push(elements: elements) + return Offset(offset: endVector(len: size)) + } + + /// Creates a vector of type Enums in the buffer + /// - Parameter elements: elements to be written into the buffer + /// - returns: Offset of the vector + mutating public func createVector(_ elements: [T]) -> Offset { + createVector(elements, size: elements.count) + } + + /// Creates a vector of type Enums in the buffer + /// - Parameter elements: Elements to be written into the buffer + /// - Parameter size: Count of elements + /// - returns: Offset of the vector + mutating public func createVector(_ elements: [T], size: Int) -> Offset { + let size = size + startVector(size, elementSize: T.byteSize) + for e in elements.reversed() { + _bb.push(value: e.value, len: T.byteSize) } - - /// Adds scalars front to back instead of the default behavior of the normal add - /// - Parameters: - /// - v: element of type Scalar - /// - postion: position relative to the `writerIndex` - mutating public func reverseAdd(v: T, postion: Int) { - _bb.reversePush(value: v, - position: postion, - len: MemoryLayout.size) + return Offset(offset: endVector(len: size)) + } + + /// Creates a vector of type Offsets in the buffer + /// - Parameter offsets:Array of offsets of type T + /// - returns: Offset of the vector + mutating public func createVector(ofOffsets offsets: [Offset]) -> Offset { + createVector(ofOffsets: offsets, len: offsets.count) + } + + /// Creates a vector of type Offsets in the buffer + /// - Parameter elements: Array of offsets of type T + /// - Parameter size: Count of elements + /// - returns: Offset of the vector + mutating public func createVector(ofOffsets offsets: [Offset], len: Int) -> Offset { + startVector(len, elementSize: MemoryLayout>.size) + for o in offsets.reversed() { + push(element: o) } - - /// Ends the struct and returns the current buffer size - /// - Returns: Offset of type UOffset - @discardableResult - public func endStruct() -> Offset { - return Offset(offset: _bb.size) + return Offset(offset: endVector(len: len)) + } + + /// Creates a vector of Strings + /// - Parameter str: a vector of strings that will be written into the buffer + /// - returns: Offset of the vector + mutating public func createVector(ofStrings str: [String]) -> Offset { + var offsets: [Offset] = [] + for s in str { + offsets.append(create(string: s)) } - - /// Adds the offset of a struct into the vTable - /// - /// The function fatalErrors if we pass an offset that is out of range - /// - Parameter o: offset - mutating public func add(structOffset o: VOffset) { - _vtableStorage.add(loc: FieldLoc(offset: _bb.size, position: VOffset(o))) + return createVector(ofOffsets: offsets) + } + + /// Creates a vector of Flatbuffer structs. + /// + /// The function takes a Type to know what size it is, and alignment + /// - Parameters: + /// - structs: An array of UnsafeMutableRawPointer + /// - type: Type of the struct being written + /// - returns: Offset of the vector + @available( + *, + deprecated, + message: "0.9.0 will be removing the following method. Regenerate the code") + mutating public func createVector( + structs: [UnsafeMutableRawPointer], + type: T.Type) -> Offset + { + startVector(structs.count &* T.size, elementSize: T.alignment) + for i in structs.reversed() { + create(struct: i, type: T.self) } - - // MARK: - Inserting Strings - - /// Insets a string into the buffer using UTF8 - /// - Parameter str: String to be serialized - /// - returns: The strings offset in the buffer - 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) + return Offset(offset: endVector(len: structs.count)) + } + + /// Starts a vector of struct that considers the size and alignment of the struct + /// - Parameters: + /// - count: number of elements to be written + /// - size: size of struct + /// - alignment: alignment of the struct + mutating public func startVectorOfStructs(count: Int, size: Int, alignment: Int) { + startVector(count &* size, elementSize: alignment) + } + + /// Ends the vector of structs and writtens the current offset + /// - Parameter count: number of written elements + /// - Returns: Offset of type UOffset + mutating public func endVectorOfStructs(count: Int) -> Offset { + Offset(offset: endVector(len: count)) + } + + // MARK: - Inserting Structs + + /// Writes a Flatbuffer struct into the buffer + /// - Parameters: + /// - s: Flatbuffer struct + /// - type: Type of the element to be serialized + /// - returns: Offset of the Object + @available( + *, + deprecated, + message: "0.9.0 will be removing the following method. Regenerate the code") + @discardableResult + mutating public func create( + struct s: UnsafeMutableRawPointer, + type: T.Type) -> Offset + { + let size = T.size + preAlign(len: size, alignment: T.alignment) + _bb.push(struct: s, size: size) + return Offset(offset: _bb.size) + } + + /// prepares the ByteBuffer to receive a struct of size and alignment + /// - Parameters: + /// - size: size of written struct + /// - alignment: alignment of written struct + mutating public func createStructOf(size: Int, alignment: Int) { + preAlign(len: size, alignment: alignment) + _bb.prepareBufferToReceiveStruct(of: size) + } + + /// Adds scalars front to back instead of the default behavior of the normal add + /// - Parameters: + /// - v: element of type Scalar + /// - postion: position relative to the `writerIndex` + mutating public func reverseAdd(v: T, postion: Int) { + _bb.reversePush( + value: v, + position: postion, + len: MemoryLayout.size) + } + + /// Ends the struct and returns the current buffer size + /// - Returns: Offset of type UOffset + @discardableResult + public func endStruct() -> Offset { + Offset(offset: _bb.size) + } + + /// Adds the offset of a struct into the vTable + /// + /// The function fatalErrors if we pass an offset that is out of range + /// - Parameter o: offset + mutating public func add(structOffset o: VOffset) { + _vtableStorage.add(loc: FieldLoc(offset: _bb.size, position: VOffset(o))) + } + + // MARK: - Inserting Strings + + /// Insets a string into the buffer using UTF8 + /// - Parameter str: String to be serialized + /// - returns: The strings offset in the buffer + 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) + } + + /// Inserts a shared string to the buffer + /// + /// The function checks the stringOffsetmap if it's seen a similar string before + /// - Parameter str: String to be serialized + /// - returns: The strings offset in the buffer + mutating public func createShared(string str: String?) -> Offset { + guard let str = str else { return Offset() } + if let offset = stringOffsetMap[str] { + return offset } - - /// Inserts a shared string to the buffer - /// - /// The function checks the stringOffsetmap if it's seen a similar string before - /// - Parameter str: String to be serialized - /// - returns: The strings offset in the buffer - 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 - - /// Adds the offset of an object into the buffer - /// - Parameters: - /// - offset: Offset of another object to be written - /// - position: The predefined position of the object - 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 buffer - /// - Parameter o: Offset - /// - returns: Position of the offset - @discardableResult - mutating public func push(element o: Offset) -> UOffset { - push(element: refer(to: o.o)) - } - - // MARK: - Inserting Scalars to Buffer - - /// Adds a value into the buffer of type Scalar - /// - /// - Parameters: - /// - element: Element to insert - /// - def: Default value for that element - /// - position: The predefined position of the element - mutating public func add(element: T, def: T, at position: VOffset) { - if (element == def && !serializeDefaults) { return } - track(offset: push(element: element), at: position) - } - - /// Adds a value into the buffer of type optional Scalar - /// - Parameters: - /// - element: Optional element of type scalar - /// - position: The predefined position of the element - mutating public func add(element: T?, at position: VOffset) { - guard let element = element else { return } - track(offset: push(element: element), at: position) - } - - /// Pushes the values into the buffer - /// - Parameter element: Element to insert - /// - returns: Postion of the Element - @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 - } - + let offset = create(string: str) + stringOffsetMap[str] = offset + return offset + } + + // MARK: - Inseting offsets + + /// Adds the offset of an object into the buffer + /// - Parameters: + /// - offset: Offset of another object to be written + /// - position: The predefined position of the object + 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 buffer + /// - Parameter o: Offset + /// - returns: Position of the offset + @discardableResult + mutating public func push(element o: Offset) -> UOffset { + push(element: refer(to: o.o)) + } + + // MARK: - Inserting Scalars to Buffer + + /// Adds a value into the buffer of type Scalar + /// + /// - Parameters: + /// - element: Element to insert + /// - def: Default value for that element + /// - position: The predefined position of the element + mutating public func add(element: T, def: T, at position: VOffset) { + if element == def && !serializeDefaults { return } + track(offset: push(element: element), at: position) + } + + /// Adds a value into the buffer of type optional Scalar + /// - Parameters: + /// - element: Optional element of type scalar + /// - position: The predefined position of the element + mutating public func add(element: T?, at position: VOffset) { + guard let element = element else { return } + track(offset: push(element: element), at: position) + } + + /// Pushes the values into the buffer + /// - Parameter element: Element to insert + /// - returns: Postion of the Element + @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) } - """ + + public var debugDescription: String { + """ + buffer debug: + \(_bb) + builder debug: + { finished: \(finished), serializeDefaults: \(serializeDefaults), isNested: \(isNested) } + """ + } + + /// 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 + /// the amount of added elements into the buffer + var addedElements: Int { capacity - (numOfFields &* size) } + + /// Creates the memory to store the buffer in + init() { + memory = UnsafeMutableRawBufferPointer.allocate(byteCount: 0, alignment: 0) } - /// 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 - /// the amount of added elements into the buffer - var addedElements: Int { return capacity - (numOfFields &* size) } - - /// Creates the memory to store the buffer in - init() { - memory = UnsafeMutableRawBufferPointer.allocate(byteCount: 0, alignment: 0) - } - - deinit { - memory.deallocate() - } - - /// Builds a buffer with byte count of fieldloc.size * count of field numbers - /// - Parameter count: number of fields to be written - 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 - 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 - 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 - func ensure(space: Int) { - guard space &+ writtenIndex > capacity else { return } - memory.deallocate() - memory = UnsafeMutableRawBufferPointer.allocate(byteCount: space, alignment: size) - capacity = space - } + deinit { + memory.deallocate() + } - /// Loads an object of type `FieldLoc` from buffer memory - /// - Parameter index: index of element - /// - Returns: a FieldLoc at index - func load(at index: Int) -> FieldLoc { - return memory.load(fromByteOffset: index, as: FieldLoc.self) - } - + /// Builds a buffer with byte count of fieldloc.size * count of field numbers + /// - Parameter count: number of fields to be written + func start(count: Int) { + assert(count >= 0, "number of fields should NOT be negative") + let capacity = count &* size + ensure(space: capacity) } - - internal struct FieldLoc { - var offset: UOffset - var position: VOffset + + /// Adds a FieldLoc into the buffer, which would track how many have been written, + /// and max offset + /// - Parameter loc: Location of encoded element + 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 + 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 + 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 + func load(at index: Int) -> FieldLoc { + memory.load(fromByteOffset: index, as: FieldLoc.self) + } + + } + + internal struct FieldLoc { + var offset: UOffset + var position: VOffset + } + } diff --git a/swift/Sources/FlatBuffers/FlatBufferObject.swift b/swift/Sources/FlatBuffers/FlatBufferObject.swift index 52ca396ad..7536c405b 100644 --- a/swift/Sources/FlatBuffers/FlatBufferObject.swift +++ b/swift/Sources/FlatBuffers/FlatBufferObject.swift @@ -1,15 +1,31 @@ +/* + * 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 Foundation /// FlatbufferObject structures all the Flatbuffers objects public protocol FlatBufferObject { - var __buffer: ByteBuffer! { get } - init(_ bb: ByteBuffer, o: Int32) + var __buffer: ByteBuffer! { get } + init(_ bb: ByteBuffer, o: Int32) } public protocol ObjectAPI { - associatedtype T - static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset - mutating func unpack() -> T + associatedtype T + static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset + mutating func unpack() -> T } /// Readable is structures all the Flatbuffers structs @@ -17,12 +33,12 @@ public protocol ObjectAPI { /// Readable is a procotol that each Flatbuffer struct should confirm to since /// FlatBufferBuilder would require a Type to both create(struct:) and createVector(structs:) functions public protocol Readable: FlatBufferObject { - static var size: Int { get } - static var alignment: Int { get } + static var size: Int { get } + static var alignment: Int { get } } public protocol Enum { - associatedtype T: Scalar - static var byteSize: Int { get } - var value: T { get } + associatedtype T: Scalar + static var byteSize: Int { get } + var value: T { get } } diff --git a/swift/Sources/FlatBuffers/FlatBuffersUtils.swift b/swift/Sources/FlatBuffers/FlatBuffersUtils.swift index 6838f8623..507ef67cf 100644 --- a/swift/Sources/FlatBuffers/FlatBuffersUtils.swift +++ b/swift/Sources/FlatBuffers/FlatBuffersUtils.swift @@ -1,16 +1,32 @@ +/* + * 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 Foundation public final class FlatBuffersUtils { - - /// Gets the size of the prefix - /// - Parameter bb: Flatbuffer object - public static func getSizePrefix(bb: ByteBuffer) -> Int32 { - return bb.read(def: Int32.self, position: bb.reader) - } - - /// Removes the prefix by duplicating the Flatbuffer - /// - Parameter bb: Flatbuffer object - public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer { - return bb.duplicate(removing: MemoryLayout.size) - } + + /// 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 + /// - Parameter bb: Flatbuffer object + public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer { + bb.duplicate(removing: MemoryLayout.size) + } } diff --git a/swift/Sources/FlatBuffers/Int+extension.swift b/swift/Sources/FlatBuffers/Int+extension.swift index e52bdab62..ed68ca08b 100644 --- a/swift/Sources/FlatBuffers/Int+extension.swift +++ b/swift/Sources/FlatBuffers/Int+extension.swift @@ -1,31 +1,47 @@ +/* + * 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 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) + /// 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/swift/Sources/FlatBuffers/Message.swift b/swift/Sources/FlatBuffers/Message.swift index 590d3d7fc..d1db35765 100644 --- a/swift/Sources/FlatBuffers/Message.swift +++ b/swift/Sources/FlatBuffers/Message.swift @@ -1,41 +1,59 @@ +/* + * 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. + */ + 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) + + /// 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 final class 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 { return buffer.memory.advanced(by: buffer.reader) } - - public var size: Int { return 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() - } + 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/swift/Sources/FlatBuffers/Mutable.swift b/swift/Sources/FlatBuffers/Mutable.swift index 90c1d8b10..adcaa1f44 100644 --- a/swift/Sources/FlatBuffers/Mutable.swift +++ b/swift/Sources/FlatBuffers/Mutable.swift @@ -1,67 +1,83 @@ +/* + * 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 Foundation /// Mutable is a protocol that allows us to mutate Scalar values within the buffer public protocol Mutable { - /// makes Flatbuffer accessed within the Protocol - var bb: ByteBuffer { get } - /// makes position of the table/struct accessed within the Protocol - var postion: Int32 { get } + /// makes Flatbuffer accessed within the Protocol + var bb: ByteBuffer { get } + /// makes position of the table/struct accessed within the Protocol + var postion: Int32 { get } } extension Mutable { - - /// Mutates the memory in the buffer, this is only called from the access function of table and structs - /// - 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 - } + + /// Mutates the memory in the buffer, this is only called from the access function of table and structs + /// - 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 the 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 + postion) - } - - /// 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 { - return mutate(value: value, o: index) - } + + /// Mutates a value by calling mutate with respect to the position in the 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 + postion) + } + + /// 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 { - return mutate(value: value, o: index + postion) - } - - /// 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 { - return mutate(value: value, o: index) - } + + /// 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 + postion) + } + + /// 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 {} diff --git a/swift/Sources/FlatBuffers/NativeTable.swift b/swift/Sources/FlatBuffers/NativeTable.swift index 057b3766e..5c844c1b3 100644 --- a/swift/Sources/FlatBuffers/NativeTable.swift +++ b/swift/Sources/FlatBuffers/NativeTable.swift @@ -1,29 +1,45 @@ +/* + * 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 Foundation public protocol NativeTable {} extension NativeTable { - - /// Serialize is a helper function that serailizes 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 serailizes 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 - } + + /// Serialize is a helper function that serailizes 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 serailizes 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/swift/Sources/FlatBuffers/Offset.swift b/swift/Sources/FlatBuffers/Offset.swift index cdb02278b..4b42b0433 100644 --- a/swift/Sources/FlatBuffers/Offset.swift +++ b/swift/Sources/FlatBuffers/Offset.swift @@ -1,12 +1,28 @@ +/* + * 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 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 { return o == 0 } - - public init(offset: UOffset) { o = offset } - public init() { o = 0 } + /// 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/swift/Sources/FlatBuffers/Struct.swift b/swift/Sources/FlatBuffers/Struct.swift index 88e3a41a2..73b3295d7 100644 --- a/swift/Sources/FlatBuffers/Struct.swift +++ b/swift/Sources/FlatBuffers/Struct.swift @@ -1,16 +1,32 @@ +/* + * 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 Foundation public struct Struct { - public private(set) var bb: ByteBuffer - public private(set) var postion: Int32 - - public init(bb: ByteBuffer, position: Int32 = 0) { - self.bb = bb - self.postion = position - } - - public func readBuffer(of type: T.Type, at o: Int32) -> T { - let r = bb.read(def: T.self, position: Int(o + postion)) - return r - } + public private(set) var bb: ByteBuffer + public private(set) var postion: Int32 + + public init(bb: ByteBuffer, position: Int32 = 0) { + self.bb = bb + postion = position + } + + public func readBuffer(of type: T.Type, at o: Int32) -> T { + let r = bb.read(def: T.self, position: Int(o + postion)) + return r + } } diff --git a/swift/Sources/FlatBuffers/Table.swift b/swift/Sources/FlatBuffers/Table.swift index 0f783bfeb..451398cd5 100644 --- a/swift/Sources/FlatBuffers/Table.swift +++ b/swift/Sources/FlatBuffers/Table.swift @@ -1,144 +1,166 @@ +/* + * 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 Foundation public struct Table { - public private(set) var bb: ByteBuffer - public private(set) var postion: Int32 - - 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.postion = position - } - - public func offset(_ o: Int32) -> Int32 { - let vtable = postion - bb.read(def: Int32.self, position: Int(postion)) - return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read(def: Int16.self, position: Int(vtable + o))) : 0 - } - - public func indirect(_ o: Int32) -> Int32 { return o + bb.read(def: Int32.self, position: Int(o)) } + public private(set) var bb: ByteBuffer + public private(set) var postion: Int32 - /// 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? { - return directString(at: offset + postion) - } - - /// 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 = offset + Int32(MemoryLayout.size) - return bb.readString(at: position, count: count) - } - - /// Reads from the buffer with respect to the position in the table. - /// - Parameters: - /// - type: Type of Scalar that needs to be read from the buffer - /// - o: Offset of the Element - public func readBuffer(of type: T.Type, at o: Int32) -> T { - return directRead(of: T.self, offset: o + postion) - } - - /// 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 Scalar 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 - } - - public func union(_ o: Int32) -> T { - let o = o + postion - return directUnion(o) + 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 + postion = position + } - public func directUnion(_ o: Int32) -> T { - return T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) - } - - public func getVector(at off: Int32) -> [T]? { - let o = offset(off) - guard o != 0 else { return nil } - return bb.readSlice(index: vector(at: o), count: 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 += postion - 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 += postion - return o + bb.read(def: Int32.self, position: Int(o)) + 4 - } + public func offset(_ o: Int32) -> Int32 { + let vtable = postion - bb.read(def: Int32.self, position: Int(postion)) + return o < bb.read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read( + def: Int16.self, + position: Int(vtable + o))) : 0 + } + + 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 + postion) + } + + /// 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 = offset + Int32(MemoryLayout.size) + return bb.readString(at: position, count: count) + } + + /// Reads from the buffer with respect to the position in the table. + /// - Parameters: + /// - type: Type of Scalar 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 + postion) + } + + /// 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 Scalar 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 + } + + public func union(_ o: Int32) -> T { + let o = o + postion + return directUnion(o) + } + + public func directUnion(_ o: Int32) -> T { + T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) + } + + public func getVector(at off: Int32) -> [T]? { + let o = offset(off) + guard o != 0 else { return nil } + return bb.readSlice(index: vector(at: o), count: 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 += postion + 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 += postion + return o + bb.read(def: Int32.self, position: Int(o)) + 4 + } } extension Table { - - static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { return o + fbb.read(def: Int32.self, position: Int(o)) } - - 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))))) + + static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { o + fbb.read( + def: Int32.self, + position: Int(o)) } + + 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))))) + } + + 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) + } } - - 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 - } - - 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.. 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.. Void) -> Benchmark { + action() + let start = CFAbsoluteTimeGetCurrent() + for _ in 0.. String { - let separator = "-------------------------------------" - var document = "\(separator)\n" - document += "\(String(format: "|\t%@\t\t|\t\t%@\t\t|", "Name", "Scores"))\n" + let separator = "-------------------------------------" + var document = "\(separator)\n" + document += "\(String(format: "|\t%@\t\t|\t\t%@\t\t|", "Name", "Scores"))\n" + document += "\(separator)\n" + for i in Benchmarks { + document += "\(i.description) \n" document += "\(separator)\n" - for i in Benchmarks { - document += "\(i.description) \n" - document += "\(separator)\n" - } - return document + } + return document } -@inlinable func create10Strings() { - var fb = FlatBufferBuilder(initialSize: 1<<20) - for _ in 0..<10_000 { - _ = fb.create(string: "foobarbaz") - } +@inlinable +func create10Strings() { + var fb = FlatBufferBuilder(initialSize: 1<<20) + for _ in 0..<10_000 { + _ = fb.create(string: "foobarbaz") + } } -@inlinable func create100Strings(str: String) { - var fb = FlatBufferBuilder(initialSize: 1<<20) - for _ in 0..<10_000 { - _ = fb.create(string: str) - } +@inlinable +func create100Strings(str: String) { + var fb = FlatBufferBuilder(initialSize: 1<<20) + for _ in 0..<10_000 { + _ = fb.create(string: str) + } } -@inlinable func benchmarkFiveHundredAdds() { - var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) - for _ in 0..<500_000 { - 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) - _ = fb.endTable(at: s) - } +@inlinable +func benchmarkFiveHundredAdds() { + var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) + for _ in 0..<500_000 { + 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) + _ = fb.endTable(at: s) + } } -@inlinable func benchmarkThreeMillionStructs() { - let structCount = 3_000_000 - - let rawSize = ((16 * 5) * structCount) / 1024 - - var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) - - var offsets: [Offset] = [] - for _ in 0..(offset: fb.endTable(at: start))) +@inlinable +func benchmarkThreeMillionStructs() { + let structCount = 3_000_000 + + let rawSize = ((16 * 5) * structCount) / 1024 + + var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) + + var offsets: [Offset] = [] + for _ in 0..(offset: fb.endTable(at: start)) - fb.finish(offset: root) + 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) } func benchmark(numberOfRuns runs: Int) { - var benchmarks: [Benchmark] = [] - let str = (0...99).map { _ -> String in return "x" }.joined() - benchmarks.append(run(name: "500_000", runs: runs, action: benchmarkFiveHundredAdds)) - benchmarks.append(run(name: "10 str", runs: runs, action: create10Strings)) - let hundredStr = run(name: "100 str", runs: runs) { - create100Strings(str: str) - } - benchmarks.append(run(name: "3M strc", runs: 1, action: benchmarkThreeMillionStructs)) - benchmarks.append(hundredStr) - print(createDocument(Benchmarks: benchmarks)) + var benchmarks: [Benchmark] = [] + let str = (0...99).map { _ -> String in "x" }.joined() + benchmarks.append(run(name: "500_000", runs: runs, action: benchmarkFiveHundredAdds)) + benchmarks.append(run(name: "10 str", runs: runs, action: create10Strings)) + let hundredStr = run(name: "100 str", runs: runs) { + create100Strings(str: str) + } + benchmarks.append(run(name: "3M strc", runs: 1, action: benchmarkThreeMillionStructs)) + benchmarks.append(hundredStr) + print(createDocument(Benchmarks: benchmarks)) } benchmark(numberOfRuns: 20) diff --git a/tests/FlatBuffers.GRPC.Swift/Package.swift b/tests/FlatBuffers.GRPC.Swift/Package.swift index f68c24129..ee9adc23c 100644 --- a/tests/FlatBuffers.GRPC.Swift/Package.swift +++ b/tests/FlatBuffers.GRPC.Swift/Package.swift @@ -1,48 +1,58 @@ // swift-tools-version:5.1 -// The swift-tools-version declares the minimum version of Swift required to build this package. +/* + * 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.GRPC.Swift", - platforms: [ - .iOS(.v11), - .macOS(.v10_14), - ], - dependencies: [ - .package(path: "../../swift"), - .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19") - ], - targets: [ - // Targets are the basic building blocks of a package. A target can define a module or a test suite. - // Targets can depend on other targets in this package, and on products in packages which this package depends on. - .target( - name: "Model", - dependencies: [ - "GRPC", - "FlatBuffers" - ], - path: "Sources/Model" - ), - - // Client for the Greeter example - .target( - name: "Client", - dependencies: [ - "GRPC", - "Model", - ], - path: "Sources/client" - ), - - // Server for the Greeter example - .target( - name: "Server", - dependencies: [ - "GRPC", - "Model", - ], - path: "Sources/server" - ), - ] -) + name: "FlatBuffers.GRPC.Swift", + platforms: [ + .iOS(.v11), + .macOS(.v10_14), + ], + dependencies: [ + .package(path: "../../swift"), + .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19"), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "Model", + dependencies: [ + "GRPC", + "FlatBuffers", + ], + path: "Sources/Model"), + + // Client for the Greeter example + .target( + name: "Client", + dependencies: [ + "GRPC", + "Model", + ], + path: "Sources/client"), + + // Server for the Greeter example + .target( + name: "Server", + dependencies: [ + "GRPC", + "Model", + ], + path: "Sources/server"), + ]) diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift index f3c4b6755..e4605e03d 100644 --- a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift +++ b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter.grpc.swift @@ -1,6 +1,10 @@ // 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 @@ -9,67 +13,65 @@ 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) - } + 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 GreeterServiceClient, then call methods of this protocol to make API calls. public protocol GreeterService { - func SayHello(_ request: Message, callOptions: CallOptions?) -> UnaryCall,Message> - func SayManyHellos(_ request: Message, callOptions: CallOptions?, handler: @escaping (Message) -> Void) -> ServerStreamingCall, Message> + func SayHello(_ request: Message, callOptions: CallOptions?) -> UnaryCall,Message> + func SayManyHellos(_ request: Message, callOptions: CallOptions?, handler: @escaping (Message) -> Void) -> ServerStreamingCall, Message> } public final class GreeterServiceClient: GRPCClient, GreeterService { - public let channel: GRPCChannel - public var defaultCallOptions: CallOptions + public let channel: GRPCChannel + public var defaultCallOptions: CallOptions - public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { - self.channel = channel - self.defaultCallOptions = defaultCallOptions - } + public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + } - public func SayHello(_ request: Message, callOptions: CallOptions? = nil) -> UnaryCall,Message> { - return self.makeUnaryCall(path: "/Greeter/SayHello", request: request, callOptions: callOptions ?? self.defaultCallOptions) - } + public func SayHello(_ request: Message, callOptions: CallOptions? = nil) -> UnaryCall,Message> { + return self.makeUnaryCall(path: "/Greeter/SayHello", request: request, callOptions: callOptions ?? self.defaultCallOptions) + } - public func SayManyHellos(_ request: Message, callOptions: CallOptions? = nil, handler: @escaping (Message) -> Void) -> ServerStreamingCall, Message> { - return self.makeServerStreamingCall(path: "/Greeter/SayManyHellos", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler) - } + public func SayManyHellos(_ request: Message, callOptions: CallOptions? = nil, handler: @escaping (Message) -> Void) -> ServerStreamingCall, Message> { + return self.makeServerStreamingCall(path: "/Greeter/SayManyHellos", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler) + } } public protocol GreeterProvider: CallHandlerProvider { - func SayHello(_ request: Message, context: StatusOnlyCallContext) -> EventLoopFuture> - func SayManyHellos(request: Message, context: StreamingResponseCallContext>) -> EventLoopFuture + func SayHello(_ request: Message, context: StatusOnlyCallContext) -> EventLoopFuture> + func SayManyHellos(request: Message, context: StreamingResponseCallContext>) -> EventLoopFuture } public extension GreeterProvider { - var serviceName: Substring { return "Greeter" } + var serviceName: Substring { return "Greeter" } - func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? { - switch methodName { - case "SayHello": - return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in - return { request in - self.SayHello(request, context: context) - } - } - case "SayManyHellos": - return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in - return { request in - self.SayManyHellos(request: request, context: context) - } - } - default: return nil; - } - } + func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? { + switch methodName { + case "SayHello": + return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in + return { request in + self.SayHello(request, context: context) + } + } + case "SayManyHellos": + return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in + return { request in + self.SayManyHellos(request: request, context: context) + } + } + default: return nil; + } + } } - - diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift index 7cb5761ba..07af658a3 100644 --- a/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift +++ b/tests/FlatBuffers.GRPC.Swift/Sources/Model/greeter_generated.swift @@ -1,106 +1,107 @@ // automatically generated by the FlatBuffers compiler, do not modify // swiftlint:disable all +// swiftformat:disable all import FlatBuffers public struct HelloReply: FlatBufferObject { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func getRootAsHelloReply(bb: ByteBuffer) -> HelloReply { return HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func getRootAsHelloReply(bb: ByteBuffer) -> HelloReply { return HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private enum VTOFFSET: VOffset { - case message = 4 - var v: Int32 { Int32(self.rawValue) } - var p: VOffset { self.rawValue } - } + private enum VTOFFSET: VOffset { + case message = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } - public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) } - public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) } - public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) } - public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } - public static func createHelloReply( - _ fbb: inout FlatBufferBuilder, - offsetOfMessage message: Offset = Offset() - ) -> Offset { - let __start = HelloReply.startHelloReply(&fbb) - HelloReply.add(message: message, &fbb) - return HelloReply.endHelloReply(&fbb, start: __start) - } + public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) } + public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) } + public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) } + public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createHelloReply( + _ fbb: inout FlatBufferBuilder, + offsetOfMessage message: Offset = Offset() + ) -> Offset { + let __start = HelloReply.startHelloReply(&fbb) + HelloReply.add(message: message, &fbb) + return HelloReply.endHelloReply(&fbb, start: __start) + } } public struct HelloRequest: FlatBufferObject { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func getRootAsHelloRequest(bb: ByteBuffer) -> HelloRequest { return HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func getRootAsHelloRequest(bb: ByteBuffer) -> HelloRequest { return HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private enum VTOFFSET: VOffset { - case name = 4 - var v: Int32 { Int32(self.rawValue) } - var p: VOffset { self.rawValue } - } + private enum VTOFFSET: VOffset { + case name = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } - public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) } - public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } - public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } - public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } - public static func createHelloRequest( - _ fbb: inout FlatBufferBuilder, - offsetOfName name: Offset = Offset() - ) -> Offset { - let __start = HelloRequest.startHelloRequest(&fbb) - HelloRequest.add(name: name, &fbb) - return HelloRequest.endHelloRequest(&fbb, start: __start) - } + public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) } + public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createHelloRequest( + _ fbb: inout FlatBufferBuilder, + offsetOfName name: Offset = Offset() + ) -> Offset { + let __start = HelloRequest.startHelloRequest(&fbb) + HelloRequest.add(name: name, &fbb) + return HelloRequest.endHelloRequest(&fbb, start: __start) + } } public struct ManyHellosRequest: FlatBufferObject { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func getRootAsManyHellosRequest(bb: ByteBuffer) -> ManyHellosRequest { return ManyHellosRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func getRootAsManyHellosRequest(bb: ByteBuffer) -> ManyHellosRequest { return ManyHellosRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } - private enum VTOFFSET: VOffset { - case name = 4 - case numGreetings = 6 - var v: Int32 { Int32(self.rawValue) } - var p: VOffset { self.rawValue } - } + private enum VTOFFSET: VOffset { + case name = 4 + case numGreetings = 6 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } - public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) } - public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) } - public var numGreetings: Int32 { let o = _accessor.offset(VTOFFSET.numGreetings.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } - public static func startManyHellosRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) } - public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } - public static func add(numGreetings: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numGreetings, def: 0, at: VTOFFSET.numGreetings.p) } - public static func endManyHellosRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } - public static func createManyHellosRequest( - _ fbb: inout FlatBufferBuilder, - offsetOfName name: Offset = Offset(), - numGreetings: Int32 = 0 - ) -> Offset { - let __start = ManyHellosRequest.startManyHellosRequest(&fbb) - ManyHellosRequest.add(name: name, &fbb) - ManyHellosRequest.add(numGreetings: numGreetings, &fbb) - return ManyHellosRequest.endManyHellosRequest(&fbb, start: __start) - } + public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) } + public var numGreetings: Int32 { let o = _accessor.offset(VTOFFSET.numGreetings.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + public static func startManyHellosRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func add(numGreetings: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numGreetings, def: 0, at: VTOFFSET.numGreetings.p) } + public static func endManyHellosRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createManyHellosRequest( + _ fbb: inout FlatBufferBuilder, + offsetOfName name: Offset = Offset(), + numGreetings: Int32 = 0 + ) -> Offset { + let __start = ManyHellosRequest.startManyHellosRequest(&fbb) + ManyHellosRequest.add(name: name, &fbb) + ManyHellosRequest.add(numGreetings: numGreetings, &fbb) + return ManyHellosRequest.endManyHellosRequest(&fbb, start: __start) + } } diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift b/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift index 74729e7e3..db3206c38 100644 --- a/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift +++ b/tests/FlatBuffers.GRPC.Swift/Sources/client/main.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020, gRPC Authors All rights reserved. + * 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. @@ -14,88 +14,91 @@ * limitations under the License. */ +import FlatBuffers import GRPC +import Logging import Model import NIO -import Logging -import FlatBuffers // Quieten the logs. LoggingSystem.bootstrap { - var handler = StreamLogHandler.standardOutput(label: $0) - handler.logLevel = .critical - return handler + var handler = StreamLogHandler.standardOutput(label: $0) + handler.logLevel = .critical + return handler } func greet(name: String, client greeter: GreeterServiceClient) { - // Form the request with the name, if one was provided. - var builder = FlatBufferBuilder() - let name = builder.create(string: name) - let root = HelloRequest.createHelloRequest(&builder, offsetOfName: name) - builder.finish(offset: root) - - // Make the RPC call to the server. - let sayHello = greeter.SayHello(Message(builder: &builder)) + // Form the request with the name, if one was provided. + var builder = FlatBufferBuilder() + let name = builder.create(string: name) + let root = HelloRequest.createHelloRequest(&builder, offsetOfName: name) + builder.finish(offset: root) - // wait() on the response to stop the program from exiting before the response is received. - do { - let response = try sayHello.response.wait() - print("Greeter received: \(response.object.message)") - } catch { - print("Greeter failed: \(error)") - } + // Make the RPC call to the server. + let sayHello = greeter.SayHello(Message(builder: &builder)) - let surname = builder.create(string: "Name") - let manyRoot = ManyHellosRequest.createManyHellosRequest(&builder, offsetOfName: surname, numGreetings: 2) - builder.finish(offset: manyRoot) + // wait() on the response to stop the program from exiting before the response is received. + do { + let response = try sayHello.response.wait() + print("Greeter received: \(response.object.message)") + } catch { + print("Greeter failed: \(error)") + } - let call = greeter.SayManyHellos(Message(builder: &builder)) { message in - print(message.object.message) - } + let surname = builder.create(string: "Name") + let manyRoot = ManyHellosRequest.createManyHellosRequest( + &builder, + offsetOfName: surname, + numGreetings: 2) + builder.finish(offset: manyRoot) - let status = try! call.status.recover { _ in .processingError }.wait() - if status.code != .ok { - print("RPC failed: \(status)") - } + let call = greeter.SayManyHellos(Message(builder: &builder)) { message in + print(message.object.message) + } + + let status = try! call.status.recover { _ in .processingError }.wait() + if status.code != .ok { + print("RPC failed: \(status)") + } } func main(args: [String]) { - // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be - // the name sent in the request. - let arg1 = args.dropFirst(1).first - let arg2 = args.dropFirst(2).first - - switch (arg1.flatMap(Int.init), arg2) { - case (.none, _): - print("Usage: PORT [NAME]") - exit(1) - - case let (.some(port), name): - // Setup an `EventLoopGroup` for the connection to run on. - // - // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups - let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) - - // Make sure the group is shutdown when we're done with it. - defer { - try! group.syncShutdownGracefully() - } - - // Configure the channel, we're not using TLS so the connection is `insecure`. - let channel = ClientConnection.insecure(group: group) - .connect(host: "localhost", port: port) + // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be + // the name sent in the request. + let arg1 = args.dropFirst(1).first + let arg2 = args.dropFirst(2).first - // Close the connection when we're done with it. - defer { - try! channel.close().wait() - } + switch (arg1.flatMap(Int.init), arg2) { + case (.none, _): + print("Usage: PORT [NAME]") + exit(1) - // Provide the connection to the generated client. - let greeter = GreeterServiceClient(channel: channel) + case let (.some(port), name): + // Setup an `EventLoopGroup` for the connection to run on. + // + // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) - // Do the greeting. - greet(name: name ?? "Hello FlatBuffers!", client: greeter) + // Make sure the group is shutdown when we're done with it. + defer { + try! group.syncShutdownGracefully() } + + // Configure the channel, we're not using TLS so the connection is `insecure`. + let channel = ClientConnection.insecure(group: group) + .connect(host: "localhost", port: port) + + // Close the connection when we're done with it. + defer { + try! channel.close().wait() + } + + // Provide the connection to the generated client. + let greeter = GreeterServiceClient(channel: channel) + + // Do the greeting. + greet(name: name ?? "Hello FlatBuffers!", client: greeter) + } } main(args: CommandLine.arguments) diff --git a/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift b/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift index 396c151e9..d7aa2b939 100644 --- a/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift +++ b/tests/FlatBuffers.GRPC.Swift/Sources/server/main.swift @@ -1,5 +1,5 @@ /* - * Copyright 2020, gRPC Authors All rights reserved. + * 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. @@ -14,50 +14,50 @@ * limitations under the License. */ -import GRPC -import NIO import FlatBuffers +import GRPC import Logging import Model +import NIO class Greeter: GreeterProvider { - - var hellos: [Message] = [] - - init() { - let names = ["Stranger1", "Stranger2", "Stranger4", "Stranger3", "Stranger5", "Stranger6"] - for name in names { - var builder = FlatBufferBuilder() - let off = builder.create(string: name) - let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off) - builder.finish(offset: root) - hellos.append(Message(builder: &builder)) - } - } - - func SayHello( - _ request: Message, - context: StatusOnlyCallContext - ) -> EventLoopFuture> { - let recipient = request.object.name ?? "Stranger" - var builder = FlatBufferBuilder() - let off = builder.create(string: recipient) - let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off) - builder.finish(offset: root) - return context.eventLoop.makeSucceededFuture(Message(builder: &builder)) + var hellos: [Message] = [] + + init() { + let names = ["Stranger1", "Stranger2", "Stranger4", "Stranger3", "Stranger5", "Stranger6"] + for name in names { + var builder = FlatBufferBuilder() + let off = builder.create(string: name) + let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off) + builder.finish(offset: root) + hellos.append(Message(builder: &builder)) } - - func SayManyHellos( - request: Message, - context: StreamingResponseCallContext> - ) -> EventLoopFuture { - for _ in 0.., + context: StatusOnlyCallContext) -> EventLoopFuture> + { + let recipient = request.object.name ?? "Stranger" + + var builder = FlatBufferBuilder() + let off = builder.create(string: recipient) + let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off) + builder.finish(offset: root) + return context.eventLoop.makeSucceededFuture(Message(builder: &builder)) + } + + func SayManyHellos( + request: Message, + context: StreamingResponseCallContext>) -> EventLoopFuture + { + for _ in 0.. MyGame_Example_MonsterT in + let bytes = ByteBuffer(assumingMemoryBound: memory.baseAddress!, capacity: memory.count) + var monster = Monster.getRootAsMonster(bb: bytes) + readFlatbufferMonster(monster: &monster) + let unpacked = monster.unpack() + return unpacked } - - func testReadFromOtherLanguages() { - 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 _data = ByteBuffer(data: data) - readMonster(fb: _data) - } - - func testCreateMonster() { - let bytes = createMonster(withPrefix: false) - 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]) - readMonster(fb: bytes.buffer) - mutateMonster(fb: bytes.buffer) - readMonster(fb: bytes.buffer) - } - - func testCreateMonsterResizedBuffer() { - let bytes = createMonster(withPrefix: false) - 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]) - readMonster(fb: bytes.sizedBuffer) - } - - func testCreateMonsterPrefixed() { - let bytes = createMonster(withPrefix: true) - 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]) - - let newBuf = FlatBuffersUtils.removeSizePrefix(bb: bytes.buffer) - readMonster(fb: newBuf) + readObjectApi(monster: unpacked) + } + + func readMonster(fb: ByteBuffer) { + var monster = Monster.getRootAsMonster(bb: fb) + readFlatbufferMonster(monster: &monster) + let unpacked: MyGame_Example_MonsterT? = monster.unpack() + readObjectApi(monster: unpacked!) + guard let buffer = unpacked?.serialize() else { fatalError("Couldnt generate bytebuffer") } + var newMonster = Monster.getRootAsMonster(bb: 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 size = 2 + Monster.startVectorOfTest4(size, in: &fbb) + MyGame_Example_Test.createTest(builder: &fbb, a: 10, b: 20) + MyGame_Example_Test.createTest(builder: &fbb, a: 30, b: 40) + let test4 = fbb.endVectorOfStructs(count: size) + + let stringTestVector = fbb.createVector(ofOffsets: [test1, test2]) + let mStart = Monster.startMonster(&fbb) + let posStruct = MyGame_Example_Vec3.createVec3(builder: &fbb, x: 1, y: 2, z: 3, test1: 3, test2: .green, test3a: 5, test3b: 6) + Monster.add(pos: posStruct, &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) { + let monster = Monster.getRootAsMonster(bb: 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.. MyGame_Example_MonsterT in - let bytes = ByteBuffer(assumingMemoryBound: memory.baseAddress!, capacity: memory.count) - var monster = Monster.getRootAsMonster(bb: bytes) - readFlatbufferMonster(monster: &monster) - let unpacked = monster.unpack() - return unpacked - } - readObjectApi(monster: unpacked) + func readFlatbufferMonster(monster: inout MyGame_Example_Monster) { + XCTAssertEqual(monster.hp, 80) + XCTAssertEqual(monster.mana, 150) + XCTAssertEqual(monster.name, "MyMonster") + let pos = monster.pos + XCTAssertEqual(pos?.x, 1) + XCTAssertEqual(pos?.y, 2) + XCTAssertEqual(pos?.z, 3) + XCTAssertEqual(pos?.test1, 3) + XCTAssertEqual(pos?.test2, .green) + let test = pos?.test3 + XCTAssertEqual(test?.a, 5) + XCTAssertEqual(test?.b, 6) + XCTAssertEqual(monster.testType, .monster) + let monster2 = monster.test(type: Monster.self) + XCTAssertEqual(monster2?.name, "Fred") + + XCTAssertEqual(monster.mutate(mana: 10), false) + + XCTAssertEqual(monster.mana, 150) + XCTAssertEqual(monster.inventoryCount, 5) + var sum: Byte = 0 + for i in 0...monster.inventoryCount { + sum += monster.inventory(at: i) } - - func readMonster(fb: ByteBuffer) { - var monster = Monster.getRootAsMonster(bb: fb) - readFlatbufferMonster(monster: &monster) - let unpacked: MyGame_Example_MonsterT? = monster.unpack() - readObjectApi(monster: unpacked!) - guard let buffer = unpacked?.serialize() else { fatalError("Couldnt generate bytebuffer") } - var newMonster = Monster.getRootAsMonster(bb: buffer) - readFlatbufferMonster(monster: &newMonster) + XCTAssertEqual(sum, 10) + XCTAssertEqual(monster.test4Count, 2) + let test0 = monster.test4(at: 0) + let test1 = monster.test4(at: 1) + var sum0 = 0 + var sum1 = 0 + if let a = test0?.a, let b = test0?.b { + sum0 = Int(a) + Int(b) } - - 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 size = 2 - Monster.startVectorOfTest4(size, in: &fbb) - MyGame_Example_Test.createTest(builder: &fbb, a: 10, b: 20) - MyGame_Example_Test.createTest(builder: &fbb, a: 30, b: 40) - let test4 = fbb.endVectorOfStructs(count: size) - - let stringTestVector = fbb.createVector(ofOffsets: [test1, test2]) - let mStart = Monster.startMonster(&fbb) - let posStruct = MyGame_Example_Vec3.createVec3(builder: &fbb, x: 1, y: 2, z: 3, test1: 3, test2: .green, test3a: 5, test3b: 6) - Monster.add(pos: posStruct, &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 + if let a = test1?.a, let b = test1?.b { + sum1 = Int(a) + Int(b) } - - func mutateMonster(fb: ByteBuffer) { - let monster = Monster.getRootAsMonster(bb: 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.. Offset { - builder.createStructOf(size: Vec.size, alignment: Vec.alignment) - builder.reverseAdd(v: x, postion: 0) - builder.reverseAdd(v: y, postion: 4) - builder.reverseAdd(v: z, postion: 8) - return builder.endStruct() + builder.createStructOf(size: Vec.size, alignment: Vec.alignment) + builder.reverseAdd(v: x, postion: 0) + builder.reverseAdd(v: y, postion: 4) + builder.reverseAdd(v: z, postion: 8) + return builder.endStruct() } diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift index cac174013..a60560029 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift @@ -1,141 +1,176 @@ +/* + * 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 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) - 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] - 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) - 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] - XCTAssertEqual(b.sizedByteArray, v) - } - - func testReadCountry() { - 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] - 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) - let scalarTable = optional_scalars_ScalarStuff.getRootAsScalarStuff(bb: b.sizedBuffer) - 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) - } + + 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) + 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] + 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) + 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] + XCTAssertEqual(b.sizedByteArray, v) + } + + func testReadCountry() { + 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] + 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) + let scalarTable = optional_scalars_ScalarStuff.getRootAsScalarStuff(bb: b.sizedBuffer) + 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]? { return __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 { - return 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 { - return 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 { - return 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) - } + + 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/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift index a90baae93..080227206 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift @@ -1,148 +1,172 @@ +/* + * 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 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 - 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]) - 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]) - builder.startVectorOfStructs(count: 2, size: Vec.size, alignment: Vec.alignment) - createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0) - createVecWrite(builder: &builder, x: 4.0, y: 5.0, z: 6.0) - let path = builder.endVectorOfStructs(count: 2) - let orc = FinalMonster.createMonster(builder: &builder, - position: createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0), - hp: 300, - name: name, - inventory: inv, - color: .red, - weapons: weapons, - equipment: .Weapon, - equippedOffset: weaponTwo, - path: path) - builder.finish(offset: orc) - XCTAssertEqual(builder.sizedByteArray, [32, 0, 0, 0, 0, 0, 26, 0, 36, 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]) - } - - 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) - 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]) - 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 = [ - BookReader.createBookReader(builder: &fb, booksRead: 7), - attack, - BookReader.createBookReader(builder: &fb, booksRead: 2) - ] - let types = fb.createVector(characterType) - let characterVector = fb.createVector(ofOffsets: characters) - let end = Movie.createMovie(&fb, vectorOfCharactersType: types, vectorOfCharacters: characterVector) - Movie.finish(&fb, end: end) - - var movie = Movie.getRootAsMovie(bb: fb.buffer) - XCTAssertEqual(movie.charactersTypeCount, Int32(characterType.count)) - XCTAssertEqual(movie.charactersCount, Int32(characters.count)) - - for i in 0...size } - var value: Int32 { return self.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 { return 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 RGB: Int32, Enum { + typealias T = Int32 + static var byteSize: Int { MemoryLayout.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 } + } } @@ -151,92 +175,108 @@ enum Equipment: Byte { case none, Weapon } enum Color3: Int8 { case red = 0, green, blue } struct FinalMonster { - - @inlinable static func createMonster(builder: inout FlatBufferBuilder, - position: Offset, - 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.add(structOffset: 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)) - } + + @inlinable + static func createMonster( + builder: inout FlatBufferBuilder, + position: Offset, + 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.add(structOffset: 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 { - return 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)) - } + + 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]? { return __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 { return 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 { - return 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) - } + + 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/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift index 9d63e8039..f095eef86 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift @@ -1,116 +1,133 @@ +/* + * 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 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) - 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]) - } - - 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) - 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]) - } - - 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) - 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]) - } - 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) - 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]) - } - - 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 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) + 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]) + } + + 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) + 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]) + } + + 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) + 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]) + } + 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) + 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]) + } + + 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]) + } } struct Numbers { - - private var __t: Table - - private init(_ t: Table) { - __t = t - } - - @inlinable static func getRootAsNumbers(_ bb: ByteBuffer) -> Numbers { - return Numbers(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0)))) - } - - var vArrayInt: [Int]? { return __t.getVector(at: 4) } - var vArrayInt32: [Int32]? { return __t.getVector(at: 4) } - var vArrayDouble: [Double]? { return __t.getVector(at: 4) } - var vArrayFloat: [Float32]? { return __t.getVector(at: 4) } - - static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int]) -> Offset { - return b.createVector(array, size: array.count) - } - - static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int32]) -> Offset { - return b.createVector(array, size: array.count) - } - - static func createNumbersVector(b: inout FlatBufferBuilder, array: [Double]) -> Offset { - return b.createVector(array, size: array.count) - } - - static func createNumbersVector(b: inout FlatBufferBuilder, array: [Float32]) -> Offset { - return 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)) - } + + 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/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift index 6f61ec6fd..4d6d724fe 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift @@ -1,69 +1,95 @@ +/* + * 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 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) - 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] - 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) - 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] - XCTAssertEqual(b.sizedByteArray, v) - } + + 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) + 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] + 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) + 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] + 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 { - return 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 { - return 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) - } + + 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/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift index e1d52cdf0..8459ee57c 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/XCTestManifests.swift @@ -1,93 +1,115 @@ +/* + * 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. + */ + #if !canImport(ObjectiveC) import XCTest extension FlatBuffersDoubleTests { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FlatBuffersDoubleTests = [ - ("testCreateFinish", testCreateFinish), - ("testCreateFinishWithPrefix", testCreateFinishWithPrefix), - ] + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__FlatBuffersDoubleTests = [ + ("testCreateFinish", testCreateFinish), + ("testCreateFinishWithPrefix", testCreateFinishWithPrefix), + ] } extension FlatBuffersMonsterWriterTests { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FlatBuffersMonsterWriterTests = [ - ("testCreateMonster", testCreateMonster), - ("testCreateMonsterPrefixed", testCreateMonsterPrefixed), - ("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer), - ("testCreateMonsterUsingCreateMonsterMethodWithNilPos", testCreateMonsterUsingCreateMonsterMethodWithNilPos), - ("testCreateMonsterUsingCreateMonsterMethodWithPosX", testCreateMonsterUsingCreateMonsterMethodWithPosX), - ("testData", testData), - ("testReadFromOtherLanguages", testReadFromOtherLanguages), - ("testReadMonsterFromUnsafePointerWithoutCopying", testReadMonsterFromUnsafePointerWithoutCopying), - ] + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__FlatBuffersMonsterWriterTests = [ + ("testCreateMonster", testCreateMonster), + ("testCreateMonsterPrefixed", testCreateMonsterPrefixed), + ("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer), + ( + "testCreateMonsterUsingCreateMonsterMethodWithNilPos", + testCreateMonsterUsingCreateMonsterMethodWithNilPos), + ( + "testCreateMonsterUsingCreateMonsterMethodWithPosX", + testCreateMonsterUsingCreateMonsterMethodWithPosX), + ("testData", testData), + ("testReadFromOtherLanguages", testReadFromOtherLanguages), + ( + "testReadMonsterFromUnsafePointerWithoutCopying", + testReadMonsterFromUnsafePointerWithoutCopying), + ] } extension FlatBuffersStructsTests { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FlatBuffersStructsTests = [ - ("testWritingAndMutatingBools", testWritingAndMutatingBools), - ] + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__FlatBuffersStructsTests = [ + ("testWritingAndMutatingBools", testWritingAndMutatingBools), + ] } extension FlatBuffersTests { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FlatBuffersTests = [ - ("testCreateFinish", testCreateFinish), - ("testCreateFinishWithPrefix", testCreateFinishWithPrefix), - ("testCreateString", testCreateString), - ("testEndian", testEndian), - ("testOffset", testOffset), - ("testReadCountry", testReadCountry), - ("testStartTable", testStartTable), - ("testWriteNullableStrings", testWriteNullableStrings), - ("testWriteOptionalValues", testWriteOptionalValues), - ] + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__FlatBuffersTests = [ + ("testCreateFinish", testCreateFinish), + ("testCreateFinishWithPrefix", testCreateFinishWithPrefix), + ("testCreateString", testCreateString), + ("testEndian", testEndian), + ("testOffset", testOffset), + ("testReadCountry", testReadCountry), + ("testStartTable", testStartTable), + ("testWriteNullableStrings", testWriteNullableStrings), + ("testWriteOptionalValues", testWriteOptionalValues), + ] } extension FlatBuffersUnionTests { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FlatBuffersUnionTests = [ - ("testCreateMonstor", testCreateMonstor), - ("testEndTableFinish", testEndTableFinish), - ("testEnumVector", testEnumVector), - ("testUnionVector", testUnionVector), - ] + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__FlatBuffersUnionTests = [ + ("testCreateMonstor", testCreateMonstor), + ("testEndTableFinish", testEndTableFinish), + ("testEnumVector", testEnumVector), + ("testUnionVector", testUnionVector), + ] } extension FlatBuffersVectors { - // DO NOT MODIFY: This is autogenerated, use: - // `swift test --generate-linuxmain` - // to regenerate. - static let __allTests__FlatBuffersVectors = [ - ("testCreateEmptyIntArray", testCreateEmptyIntArray), - ("testCreateIntArray", testCreateIntArray), - ("testCreateSharedStringVector", testCreateSharedStringVector), - ("testCreateVectorOfStrings", testCreateVectorOfStrings), - ("testCreatingTwoCountries", testCreatingTwoCountries), - ("testReadDoubleArray", testReadDoubleArray), - ("testReadInt32Array", testReadInt32Array), - ] + // DO NOT MODIFY: This is autogenerated, use: + // `swift test --generate-linuxmain` + // to regenerate. + static let __allTests__FlatBuffersVectors = [ + ("testCreateEmptyIntArray", testCreateEmptyIntArray), + ("testCreateIntArray", testCreateIntArray), + ("testCreateSharedStringVector", testCreateSharedStringVector), + ("testCreateVectorOfStrings", testCreateVectorOfStrings), + ("testCreatingTwoCountries", testCreatingTwoCountries), + ("testReadDoubleArray", testReadDoubleArray), + ("testReadInt32Array", testReadInt32Array), + ] } public func __allTests() -> [XCTestCaseEntry] { - return [ - testCase(FlatBuffersDoubleTests.__allTests__FlatBuffersDoubleTests), - testCase(FlatBuffersMonsterWriterTests.__allTests__FlatBuffersMonsterWriterTests), - testCase(FlatBuffersStructsTests.__allTests__FlatBuffersStructsTests), - testCase(FlatBuffersTests.__allTests__FlatBuffersTests), - testCase(FlatBuffersUnionTests.__allTests__FlatBuffersUnionTests), - testCase(FlatBuffersVectors.__allTests__FlatBuffersVectors), - ] + [ + testCase(FlatBuffersDoubleTests.__allTests__FlatBuffersDoubleTests), + testCase(FlatBuffersMonsterWriterTests.__allTests__FlatBuffersMonsterWriterTests), + testCase(FlatBuffersStructsTests.__allTests__FlatBuffersStructsTests), + testCase(FlatBuffersTests.__allTests__FlatBuffersTests), + testCase(FlatBuffersUnionTests.__allTests__FlatBuffersUnionTests), + testCase(FlatBuffersVectors.__allTests__FlatBuffersVectors), + ] } #endif diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift index b2f3ff27c..414a816d6 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift @@ -1,6 +1,10 @@ // 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 @@ -9,87 +13,85 @@ 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) - } + 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_MonsterStorageService { - 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> + 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> } public final class MyGame_Example_MonsterStorageServiceClient: GRPCClient, MyGame_Example_MonsterStorageService { - public let channel: GRPCChannel - public var defaultCallOptions: CallOptions + public let channel: GRPCChannel + public var defaultCallOptions: CallOptions - public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { - self.channel = channel - self.defaultCallOptions = defaultCallOptions - } + public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + } - public func Store(_ request: Message, callOptions: CallOptions? = nil) -> UnaryCall,Message> { - return self.makeUnaryCall(path: "/MyGame.Example.MonsterStorage/Store", request: request, callOptions: callOptions ?? self.defaultCallOptions) - } + public func Store(_ request: Message, callOptions: CallOptions? = nil) -> UnaryCall,Message> { + return self.makeUnaryCall(path: "/MyGame.Example.MonsterStorage/Store", request: request, callOptions: callOptions ?? self.defaultCallOptions) + } - 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, handler: handler) - } + 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, handler: handler) + } - public func GetMaxHitPoint(callOptions: CallOptions? = nil) -> ClientStreamingCall,Message> { - return self.makeClientStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", callOptions: callOptions ?? self.defaultCallOptions) - } + public func GetMaxHitPoint(callOptions: CallOptions? = nil) -> ClientStreamingCall,Message> { + return self.makeClientStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", callOptions: callOptions ?? self.defaultCallOptions) + } - public func GetMinMaxHitPoints(callOptions: CallOptions? = nil, handler: @escaping (Message) -> Void) -> BidirectionalStreamingCall, Message> { - return self.makeBidirectionalStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", callOptions: callOptions ?? self.defaultCallOptions, handler: handler) - } + public func GetMinMaxHitPoints(callOptions: CallOptions? = nil, handler: @escaping (Message) -> Void) -> BidirectionalStreamingCall, Message> { + return self.makeBidirectionalStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", callOptions: callOptions ?? self.defaultCallOptions, handler: handler) + } } public protocol MyGame_Example_MonsterStorageProvider: CallHandlerProvider { - 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> + 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" } + var serviceName: Substring { return "MyGame.Example.MonsterStorage" } - func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? { - switch methodName { - case "Store": - return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in - return { request in - self.Store(request, context: context) - } - } - case "Retrieve": - return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in - return { request in - self.Retrieve(request: request, context: context) - } - } - case "GetMaxHitPoint": - return CallHandlerFactory.makeClientStreaming(callHandlerContext: callHandlerContext) { context in - self.GetMaxHitPoint(context: context) - } - case "GetMinMaxHitPoints": - return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in - self.GetMinMaxHitPoints(context: context) - } - default: return nil; - } - } + func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? { + switch methodName { + case "Store": + return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in + return { request in + self.Store(request, context: context) + } + } + case "Retrieve": + return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in + return { request in + self.Retrieve(request: request, context: context) + } + } + case "GetMaxHitPoint": + return CallHandlerFactory.makeClientStreaming(callHandlerContext: callHandlerContext) { context in + self.GetMaxHitPoint(context: context) + } + case "GetMinMaxHitPoints": + return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in + self.GetMinMaxHitPoints(context: context) + } + default: return nil; + } + } } - - diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift index 987f078b7..b15eddf3f 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift @@ -1,1484 +1,1485 @@ // 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 { - 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 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 } + public static var max: MyGame_Example_Color { return .blue } + public static var min: MyGame_Example_Color { return .red } } public enum MyGame_Example_Race: Int8, Enum { - 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 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_ } + public static var max: MyGame_Example_Race { return .elf } + public static var min: MyGame_Example_Race { return .none_ } } public enum MyGame_Example_Any_: UInt8, Enum { - public typealias T = UInt8 - 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 typealias T = UInt8 + 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_ } + public static var max: MyGame_Example_Any_ { return .mygameExample2Monster } + public static var min: MyGame_Example_Any_ { return .none_ } } public struct MyGame_Example_Any_Union { - public var type: MyGame_Example_Any_ - public var value: NativeTable? - public init(_ v: NativeTable?, 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 var type: MyGame_Example_Any_ + public var value: NativeTable? + public init(_ v: NativeTable?, 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, Enum { - public typealias T = UInt8 - 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 typealias T = UInt8 + 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_ } + public static var max: MyGame_Example_AnyUniqueAliases { return .m2 } + public static var min: MyGame_Example_AnyUniqueAliases { return .none_ } } public struct MyGame_Example_AnyUniqueAliasesUnion { - public var type: MyGame_Example_AnyUniqueAliases - public var value: NativeTable? - public init(_ v: NativeTable?, 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 var type: MyGame_Example_AnyUniqueAliases + public var value: NativeTable? + public init(_ v: NativeTable?, 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, Enum { - public typealias T = UInt8 - 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 typealias T = UInt8 + 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_ } + public static var max: MyGame_Example_AnyAmbiguousAliases { return .m3 } + public static var min: MyGame_Example_AnyAmbiguousAliases { return .none_ } } public struct MyGame_Example_AnyAmbiguousAliasesUnion { - public var type: MyGame_Example_AnyAmbiguousAliases - public var value: NativeTable? - public init(_ v: NativeTable?, 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 var type: MyGame_Example_AnyAmbiguousAliases + public var value: NativeTable? + public init(_ v: NativeTable?, 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: Readable { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Struct + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct - public static var size = 4 - public static var alignment = 2 - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + public static var size = 4 + public static var alignment = 2 + 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 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_TestT { - return MyGame_Example_TestT(&self) - } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestT?) -> Offset { - guard var obj = obj else { return Offset() } - return pack(&builder, obj: &obj) - } + public mutating func unpack() -> MyGame_Example_TestT { + return MyGame_Example_TestT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestT) -> Offset { - return createTest(builder: &builder, a: obj.a, b: obj.b) - } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestT) -> Offset { + return createTest(builder: &builder, a: obj.a, b: obj.b) + } } public class MyGame_Example_TestT: NativeTable { - public var a: Int16 - public var b: Int8 + public var a: Int16 + public var b: Int8 - public init(_ _t: inout MyGame_Example_Test) { - a = _t.a - b = _t.b - } + public init(_ _t: inout MyGame_Example_Test) { + a = _t.a + b = _t.b + } - public init() { - a = 0 - b = 0 - } + public init() { + a = 0 + b = 0 + } } public struct MyGame_Example_Vec3: Readable { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Struct + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct - public static var size = 32 - public static var alignment = 8 - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + public static var size = 32 + public static var alignment = 8 + 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 } - public var test3: MyGame_Example_Test { return MyGame_Example_Test(_accessor.bb, o: _accessor.postion + 26) } - + 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 } + public var test3: MyGame_Example_Test { return MyGame_Example_Test(_accessor.bb, o: _accessor.postion + 26) } + - public mutating func unpack() -> MyGame_Example_Vec3T { - return MyGame_Example_Vec3T(&self) - } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3T?) -> Offset { - guard var obj = obj else { return Offset() } - return pack(&builder, obj: &obj) - } + public mutating func unpack() -> MyGame_Example_Vec3T { + return MyGame_Example_Vec3T(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3T?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3T) -> Offset { - return createVec3(builder: &builder, x: obj.x, y: obj.y, z: obj.z, test1: obj.test1, test2: obj.test2, test3a: obj.test3.a, test3b: obj.test3.b) - } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3T) -> Offset { + return createVec3(builder: &builder, x: obj.x, y: obj.y, z: obj.z, test1: obj.test1, test2: obj.test2, test3a: obj.test3.a, test3b: obj.test3.b) + } } public class MyGame_Example_Vec3T: NativeTable { - public var x: Float32 - public var y: Float32 - public var z: Float32 - public var test1: Double - public var test2: MyGame_Example_Color - public var test3: MyGame_Example_TestT + public var x: Float32 + public var y: Float32 + public var z: Float32 + public var test1: Double + public var test2: MyGame_Example_Color + public var test3: MyGame_Example_TestT - public init(_ _t: inout MyGame_Example_Vec3) { - x = _t.x - y = _t.y - z = _t.z - test1 = _t.test1 - test2 = _t.test2 - var __test3 = _t.test3 - test3 = __test3.unpack() - } + public init(_ _t: inout MyGame_Example_Vec3) { + x = _t.x + y = _t.y + z = _t.z + test1 = _t.test1 + test2 = _t.test2 + var __test3 = _t.test3 + test3 = __test3.unpack() + } - public init() { - x = 0.0 - y = 0.0 - z = 0.0 - test1 = 0.0 - test2 = .red - test3 = MyGame_Example_TestT() - } + public init() { + x = 0.0 + y = 0.0 + z = 0.0 + test1 = 0.0 + test2 = .red + test3 = MyGame_Example_TestT() + } } public struct MyGame_Example_Ability: Readable { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Struct + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct - public static var size = 8 - public static var alignment = 4 - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + public static var size = 8 + public static var alignment = 4 + 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 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_AbilityT { - return MyGame_Example_AbilityT(&self) - } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_AbilityT?) -> Offset { - guard var obj = obj else { return Offset() } - return pack(&builder, obj: &obj) - } + public mutating func unpack() -> MyGame_Example_AbilityT { + return MyGame_Example_AbilityT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_AbilityT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_AbilityT) -> Offset { - return createAbility(builder: &builder, id: obj.id, distance: obj.distance) - } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_AbilityT) -> Offset { + return createAbility(builder: &builder, id: obj.id, distance: obj.distance) + } } public class MyGame_Example_AbilityT: NativeTable { - public var id: UInt32 - public var distance: UInt32 + public var id: UInt32 + public var distance: UInt32 - public init(_ _t: inout MyGame_Example_Ability) { - id = _t.id - distance = _t.distance - } + public init(_ _t: inout MyGame_Example_Ability) { + id = _t.id + distance = _t.distance + } - public init() { - id = 0 - distance = 0 - } + public init() { + id = 0 + distance = 0 + } } extension MyGame_Example_Test { - @discardableResult - public static func createTest(builder: inout FlatBufferBuilder, a: Int16 = 0, b: Int8 = 0) -> Offset { - builder.createStructOf(size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.alignment) - builder.reverseAdd(v: a, postion: 0) - builder.reverseAdd(v: b, postion: 2) - return builder.endStruct() - } + @discardableResult + public static func createTest(builder: inout FlatBufferBuilder, a: Int16 = 0, b: Int8 = 0) -> Offset { + builder.createStructOf(size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.alignment) + builder.reverseAdd(v: a, postion: 0) + builder.reverseAdd(v: b, postion: 2) + return builder.endStruct() + } } extension MyGame_Example_Vec3 { - @discardableResult - public static func createVec3(builder: inout FlatBufferBuilder, x: Float32 = 0.0, y: Float32 = 0.0, z: Float32 = 0.0, test1: Double = 0.0, test2: MyGame_Example_Color, test3a: Int16 = 0, test3b: Int8 = 0) -> Offset { - builder.createStructOf(size: MyGame_Example_Vec3.size, alignment: MyGame_Example_Vec3.alignment) - builder.reverseAdd(v: x, postion: 0) - builder.reverseAdd(v: y, postion: 4) - builder.reverseAdd(v: z, postion: 8) - builder.reverseAdd(v: test1, postion: 16) - builder.reverseAdd(v: test2.rawValue, postion: 24) - builder.reverseAdd(v: test3a, postion: 26) - builder.reverseAdd(v: test3b, postion: 28) - return builder.endStruct() - } + @discardableResult + public static func createVec3(builder: inout FlatBufferBuilder, x: Float32 = 0.0, y: Float32 = 0.0, z: Float32 = 0.0, test1: Double = 0.0, test2: MyGame_Example_Color, test3a: Int16 = 0, test3b: Int8 = 0) -> Offset { + builder.createStructOf(size: MyGame_Example_Vec3.size, alignment: MyGame_Example_Vec3.alignment) + builder.reverseAdd(v: x, postion: 0) + builder.reverseAdd(v: y, postion: 4) + builder.reverseAdd(v: z, postion: 8) + builder.reverseAdd(v: test1, postion: 16) + builder.reverseAdd(v: test2.rawValue, postion: 24) + builder.reverseAdd(v: test3a, postion: 26) + builder.reverseAdd(v: test3b, postion: 28) + return builder.endStruct() + } } extension MyGame_Example_Ability { - @discardableResult - public static func createAbility(builder: inout FlatBufferBuilder, id: UInt32 = 0, distance: UInt32 = 0) -> Offset { - builder.createStructOf(size: MyGame_Example_Ability.size, alignment: MyGame_Example_Ability.alignment) - builder.reverseAdd(v: id, postion: 0) - builder.reverseAdd(v: distance, postion: 4) - return builder.endStruct() - } + @discardableResult + public static func createAbility(builder: inout FlatBufferBuilder, id: UInt32 = 0, distance: UInt32 = 0) -> Offset { + builder.createStructOf(size: MyGame_Example_Ability.size, alignment: MyGame_Example_Ability.alignment) + builder.reverseAdd(v: id, postion: 0) + builder.reverseAdd(v: distance, postion: 4) + return builder.endStruct() + } } public struct MyGame_InParentNamespace: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - public static func getRootAsInParentNamespace(bb: ByteBuffer) -> MyGame_InParentNamespace { return MyGame_InParentNamespace(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + public static func getRootAsInParentNamespace(bb: ByteBuffer) -> MyGame_InParentNamespace { return MyGame_InParentNamespace(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 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 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 pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT) -> Offset { + let __root = MyGame_InParentNamespace.startInParentNamespace(&builder) + return MyGame_InParentNamespace.endInParentNamespace(&builder, start: __root) + } } public class MyGame_InParentNamespaceT: NativeTable { - public init(_ _t: inout MyGame_InParentNamespace) { - } + public init(_ _t: inout MyGame_InParentNamespace) { + } - public init() { - } + public init() { + } - public func serialize() -> ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) } + public func serialize() -> ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) } } public struct MyGame_Example2_Monster: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Example2_Monster { return MyGame_Example2_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Example2_Monster { return MyGame_Example2_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 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 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 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 class MyGame_Example2_MonsterT: NativeTable { - public init(_ _t: inout MyGame_Example2_Monster) { - } + public init(_ _t: inout MyGame_Example2_Monster) { + } - public init() { - } + public init() { + } - public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) } + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) } } internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - internal var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + internal var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - internal static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - internal static func getRootAsTestSimpleTableWithEnum(bb: ByteBuffer) -> MyGame_Example_TestSimpleTableWithEnum { return MyGame_Example_TestSimpleTableWithEnum(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + internal static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + internal static func getRootAsTestSimpleTableWithEnum(bb: ByteBuffer) -> MyGame_Example_TestSimpleTableWithEnum { return MyGame_Example_TestSimpleTableWithEnum(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } - } + 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 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 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 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 class MyGame_Example_TestSimpleTableWithEnumT: NativeTable { - internal var color: MyGame_Example_Color + internal var color: MyGame_Example_Color - internal init(_ _t: inout MyGame_Example_TestSimpleTableWithEnum) { - color = _t.color - } + internal init(_ _t: inout MyGame_Example_TestSimpleTableWithEnum) { + color = _t.color + } - internal init() { - color = .green - } + internal init() { + color = .green + } - internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) } + internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) } } public struct MyGame_Example_Stat: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - public static func getRootAsStat(bb: ByteBuffer) -> MyGame_Example_Stat { return MyGame_Example_Stat(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + public static func getRootAsStat(bb: ByteBuffer) -> MyGame_Example_Stat { return MyGame_Example_Stat(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } + 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, + offsetOfId 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 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() } - 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, - offsetOfId 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 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) - } + 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 class MyGame_Example_StatT: NativeTable { - public var id: String? - public var val: Int64 - public var count: UInt16 + 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(_ _t: inout MyGame_Example_Stat) { + id = _t.id + val = _t.val + count = _t.count + } - public init() { - val = 0 - count = 0 - } + public init() { + val = 0 + count = 0 + } - public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) } + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) } } public struct MyGame_Example_Referrable: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - public static func getRootAsReferrable(bb: ByteBuffer) -> MyGame_Example_Referrable { return MyGame_Example_Referrable(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + public static func getRootAsReferrable(bb: ByteBuffer) -> MyGame_Example_Referrable { return MyGame_Example_Referrable(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } - } + 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 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) + } } - 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 - } - + 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 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 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 class MyGame_Example_ReferrableT: NativeTable { - public var id: UInt64 + public var id: UInt64 - public init(_ _t: inout MyGame_Example_Referrable) { - id = _t.id - } + public init(_ _t: inout MyGame_Example_Referrable) { + id = _t.id + } - public init() { - id = 0 - } + public init() { + id = 0 + } - public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Referrable.self) } + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Referrable.self) } } /// an example documentation comment: "monster object" public struct MyGame_Example_Monster: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Example_Monster { return MyGame_Example_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + public static func getRootAsMonster(bb: ByteBuffer) -> MyGame_Example_Monster { return MyGame_Example_Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 - var v: Int32 { Int32(self.rawValue) } - var p: VOffset { self.rawValue } + 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 + 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 : MyGame_Example_Vec3(_accessor.bb, o: o + _accessor.postion) } + 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 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 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 : MyGame_Example_Test(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } + 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 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.postion)) } + 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.postion)) } + public var testbool: Bool { let o = _accessor.offset(VTOFFSET.testbool.v); return o == 0 ? false : 0 != _accessor.readBuffer(of: Byte.self, at: o) } + @discardableResult public func mutate(testbool: Byte) -> 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 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 : 0 != _accessor.directRead(of: Byte.self, offset: _accessor.vector(at: o) + index * 1) } + public var testarrayofbools: [Byte] { return _accessor.getVector(at: VTOFFSET.testarrayofbools.v) ?? [] } + public func mutate(testarrayofbools: Byte, 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 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 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 : MyGame_Example_Ability(_accessor.bb, o: _accessor.vector(at: o) + index * 8) } + 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 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 : MyGame_Example_Test(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } + 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 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.postion)) } + 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 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 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 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 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 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 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 static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 50) } + public static func add(pos: Offset?, _ fbb: inout FlatBufferBuilder) { guard pos != nil else { return }; fbb.add(structOffset: 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.startVectorOfStructs(count: size, size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.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.startVectorOfStructs(count: size, size: MyGame_Example_Ability.size, alignment: MyGame_Example_Ability.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.startVectorOfStructs(count: size, size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.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 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 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 } + MyGame_Example_Test.createTest(builder: &builder, a: _o.a, b: _o.b) + } + let __test4 = builder.endVectorOfStructs(count: 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 } + MyGame_Example_Ability.createAbility(builder: &builder, id: _o.id, distance: _o.distance) + } + let __testarrayofsortedstruct = builder.endVectorOfStructs(count: 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 } + MyGame_Example_Test.createTest(builder: &builder, a: _o.a, b: _o.b) + } + let __test5 = builder.endVectorOfStructs(count: 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) + let __root = MyGame_Example_Monster.startMonster(&builder) + MyGame_Example_Monster.add(pos: obj.pos.map { MyGame_Example_Vec3.createVec3(builder: &builder, x: $0.x, y: $0.y, z: $0.z, test1: $0.test1, test2: $0.test2, test3a: $0.test3.a, test3b: $0.test3.b) }, &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) } - public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3(_accessor.bb, o: o + _accessor.postion) } - 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 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 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 : MyGame_Example_Test(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } - 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 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.postion)) } - 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.postion)) } - public var testbool: Bool { let o = _accessor.offset(VTOFFSET.testbool.v); return o == 0 ? false : 0 != _accessor.readBuffer(of: Byte.self, at: o) } - @discardableResult public func mutate(testbool: Byte) -> 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 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 : 0 != _accessor.directRead(of: Byte.self, offset: _accessor.vector(at: o) + index * 1) } - public var testarrayofbools: [Byte] { return _accessor.getVector(at: VTOFFSET.testarrayofbools.v) ?? [] } - public func mutate(testarrayofbools: Byte, 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 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 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 : MyGame_Example_Ability(_accessor.bb, o: _accessor.vector(at: o) + index * 8) } - 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 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 : MyGame_Example_Test(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } - 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 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.postion)) } - 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 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 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 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 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 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 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 static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 50) } - public static func add(pos: Offset?, _ fbb: inout FlatBufferBuilder) { guard pos != nil else { return }; fbb.add(structOffset: 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.startVectorOfStructs(count: size, size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.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.startVectorOfStructs(count: size, size: MyGame_Example_Ability.size, alignment: MyGame_Example_Ability.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.startVectorOfStructs(count: size, size: MyGame_Example_Test.size, alignment: MyGame_Example_Test.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 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 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) + 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) } - 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 } - MyGame_Example_Test.createTest(builder: &builder, a: _o.a, b: _o.b) - } - let __test4 = builder.endVectorOfStructs(count: 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 } - MyGame_Example_Ability.createAbility(builder: &builder, id: _o.id, distance: _o.distance) - } - let __testarrayofsortedstruct = builder.endVectorOfStructs(count: 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 } - MyGame_Example_Test.createTest(builder: &builder, a: _o.a, b: _o.b) - } - let __test5 = builder.endVectorOfStructs(count: 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) - let __root = MyGame_Example_Monster.startMonster(&builder) - MyGame_Example_Monster.add(pos: obj.pos.map { MyGame_Example_Vec3.createVec3(builder: &builder, x: $0.x, y: $0.y, z: $0.z, test1: $0.test1, test2: $0.test2, test3a: $0.test3.a, test3b: $0.test3.b) }, &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) - return MyGame_Example_Monster.endMonster(&builder, start: __root) + 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) + return MyGame_Example_Monster.endMonster(&builder, start: __root) + } } public class MyGame_Example_MonsterT: NativeTable { - public var pos: MyGame_Example_Vec3T? - public var mana: Int16 - public var hp: Int16 - public var name: String - public var inventory: [UInt8] - public var color: MyGame_Example_Color - public var test: MyGame_Example_Any_Union? - public var test4: [MyGame_Example_TestT?] - public var testarrayofstring: [String?] - public var testarrayoftables: [MyGame_Example_MonsterT?] - public var enemy: MyGame_Example_MonsterT? - public var testnestedflatbuffer: [UInt8] - public var testempty: MyGame_Example_StatT? - public var testbool: Bool - public var testhashs32Fnv1: Int32 - public var testhashu32Fnv1: UInt32 - public var testhashs64Fnv1: Int64 - public var testhashu64Fnv1: UInt64 - public var testhashs32Fnv1a: Int32 - public var testhashu32Fnv1a: UInt32 - public var testhashs64Fnv1a: Int64 - public var testhashu64Fnv1a: UInt64 - public var testarrayofbools: [Bool] - public var testf: Float32 - public var testf2: Float32 - public var testf3: Float32 - public var testarrayofstring2: [String?] - public var testarrayofsortedstruct: [MyGame_Example_AbilityT?] - public var flex: [UInt8] - public var test5: [MyGame_Example_TestT?] - public var vectorOfLongs: [Int64] - public var vectorOfDoubles: [Double] - public var parentNamespaceTest: MyGame_InParentNamespaceT? - public var vectorOfReferrables: [MyGame_Example_ReferrableT?] - public var singleWeakReference: UInt64 - public var vectorOfWeakReferences: [UInt64] - public var vectorOfStrongReferrables: [MyGame_Example_ReferrableT?] - public var coOwningReference: UInt64 - public var vectorOfCoOwningReferences: [UInt64] - public var nonOwningReference: UInt64 - public var vectorOfNonOwningReferences: [UInt64] - public var anyUnique: MyGame_Example_AnyUniqueAliasesUnion? - public var anyAmbiguous: MyGame_Example_AnyAmbiguousAliasesUnion? - public var vectorOfEnums: [MyGame_Example_Color] - public var signedEnum: MyGame_Example_Race - public var testrequirednestedflatbuffer: [UInt8] + public var pos: MyGame_Example_Vec3T? + public var mana: Int16 + public var hp: Int16 + public var name: String + public var inventory: [UInt8] + public var color: MyGame_Example_Color + public var test: MyGame_Example_Any_Union? + public var test4: [MyGame_Example_TestT?] + public var testarrayofstring: [String?] + public var testarrayoftables: [MyGame_Example_MonsterT?] + public var enemy: MyGame_Example_MonsterT? + public var testnestedflatbuffer: [UInt8] + public var testempty: MyGame_Example_StatT? + public var testbool: Bool + public var testhashs32Fnv1: Int32 + public var testhashu32Fnv1: UInt32 + public var testhashs64Fnv1: Int64 + public var testhashu64Fnv1: UInt64 + public var testhashs32Fnv1a: Int32 + public var testhashu32Fnv1a: UInt32 + public var testhashs64Fnv1a: Int64 + public var testhashu64Fnv1a: UInt64 + public var testarrayofbools: [Bool] + public var testf: Float32 + public var testf2: Float32 + public var testf3: Float32 + public var testarrayofstring2: [String?] + public var testarrayofsortedstruct: [MyGame_Example_AbilityT?] + public var flex: [UInt8] + public var test5: [MyGame_Example_TestT?] + public var vectorOfLongs: [Int64] + public var vectorOfDoubles: [Double] + public var parentNamespaceTest: MyGame_InParentNamespaceT? + public var vectorOfReferrables: [MyGame_Example_ReferrableT?] + public var singleWeakReference: UInt64 + public var vectorOfWeakReferences: [UInt64] + public var vectorOfStrongReferrables: [MyGame_Example_ReferrableT?] + public var coOwningReference: UInt64 + public var vectorOfCoOwningReferences: [UInt64] + public var nonOwningReference: UInt64 + public var vectorOfNonOwningReferences: [UInt64] + public var anyUnique: MyGame_Example_AnyUniqueAliasesUnion? + public var anyAmbiguous: MyGame_Example_AnyAmbiguousAliasesUnion? + public var vectorOfEnums: [MyGame_Example_Color] + public var signedEnum: MyGame_Example_Race + public var testrequirednestedflatbuffer: [UInt8] - public init(_ _t: inout MyGame_Example_Monster) { - var __pos = _t.pos - pos = __pos?.unpack() - mana = _t.mana - hp = _t.hp - name = _t.name - inventory = [] - for index in 0..<_t.inventoryCount { - inventory.append(_t.inventory(at: index)) - } - color = _t.color - switch _t.testType { - case .monster: - var _v = _t.test(type: MyGame_Example_Monster.self) - test = MyGame_Example_Any_Union(_v?.unpack(), type: .monster) - case .testsimpletablewithenum: - var _v = _t.test(type: MyGame_Example_TestSimpleTableWithEnum.self) - test = MyGame_Example_Any_Union(_v?.unpack(), type: .testsimpletablewithenum) - case .mygameExample2Monster: - var _v = _t.test(type: MyGame_Example2_Monster.self) - test = MyGame_Example_Any_Union(_v?.unpack(), type: .mygameExample2Monster) - default: break - } - test4 = [] - for index in 0..<_t.test4Count { - var __v_ = _t.test4(at: index) - test4.append(__v_?.unpack()) - } - testarrayofstring = [] - for index in 0..<_t.testarrayofstringCount { - testarrayofstring.append(_t.testarrayofstring(at: index)) - } - testarrayoftables = [] - for index in 0..<_t.testarrayoftablesCount { - var __v_ = _t.testarrayoftables(at: index) - testarrayoftables.append(__v_?.unpack()) - } - var __enemy = _t.enemy - enemy = __enemy?.unpack() - testnestedflatbuffer = [] - for index in 0..<_t.testnestedflatbufferCount { - testnestedflatbuffer.append(_t.testnestedflatbuffer(at: index)) - } - var __testempty = _t.testempty - testempty = __testempty?.unpack() - testbool = _t.testbool - testhashs32Fnv1 = _t.testhashs32Fnv1 - testhashu32Fnv1 = _t.testhashu32Fnv1 - testhashs64Fnv1 = _t.testhashs64Fnv1 - testhashu64Fnv1 = _t.testhashu64Fnv1 - testhashs32Fnv1a = _t.testhashs32Fnv1a - testhashu32Fnv1a = _t.testhashu32Fnv1a - testhashs64Fnv1a = _t.testhashs64Fnv1a - testhashu64Fnv1a = _t.testhashu64Fnv1a - testarrayofbools = [] - for index in 0..<_t.testarrayofboolsCount { - testarrayofbools.append(_t.testarrayofbools(at: index)) - } - testf = _t.testf - testf2 = _t.testf2 - testf3 = _t.testf3 - testarrayofstring2 = [] - for index in 0..<_t.testarrayofstring2Count { - testarrayofstring2.append(_t.testarrayofstring2(at: index)) - } - testarrayofsortedstruct = [] - for index in 0..<_t.testarrayofsortedstructCount { - var __v_ = _t.testarrayofsortedstruct(at: index) - testarrayofsortedstruct.append(__v_?.unpack()) - } - flex = [] - for index in 0..<_t.flexCount { - flex.append(_t.flex(at: index)) - } - test5 = [] - for index in 0..<_t.test5Count { - var __v_ = _t.test5(at: index) - test5.append(__v_?.unpack()) - } - vectorOfLongs = [] - for index in 0..<_t.vectorOfLongsCount { - vectorOfLongs.append(_t.vectorOfLongs(at: index)) - } - vectorOfDoubles = [] - for index in 0..<_t.vectorOfDoublesCount { - vectorOfDoubles.append(_t.vectorOfDoubles(at: index)) - } - var __parentNamespaceTest = _t.parentNamespaceTest - parentNamespaceTest = __parentNamespaceTest?.unpack() - vectorOfReferrables = [] - for index in 0..<_t.vectorOfReferrablesCount { - var __v_ = _t.vectorOfReferrables(at: index) - vectorOfReferrables.append(__v_?.unpack()) - } - singleWeakReference = _t.singleWeakReference - vectorOfWeakReferences = [] - for index in 0..<_t.vectorOfWeakReferencesCount { - vectorOfWeakReferences.append(_t.vectorOfWeakReferences(at: index)) - } - vectorOfStrongReferrables = [] - for index in 0..<_t.vectorOfStrongReferrablesCount { - var __v_ = _t.vectorOfStrongReferrables(at: index) - vectorOfStrongReferrables.append(__v_?.unpack()) - } - coOwningReference = _t.coOwningReference - vectorOfCoOwningReferences = [] - for index in 0..<_t.vectorOfCoOwningReferencesCount { - vectorOfCoOwningReferences.append(_t.vectorOfCoOwningReferences(at: index)) - } - nonOwningReference = _t.nonOwningReference - vectorOfNonOwningReferences = [] - for index in 0..<_t.vectorOfNonOwningReferencesCount { - vectorOfNonOwningReferences.append(_t.vectorOfNonOwningReferences(at: index)) - } - switch _t.anyUniqueType { - case .m: - var _v = _t.anyUnique(type: MyGame_Example_Monster.self) - anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m) - case .ts: - var _v = _t.anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self) - anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .ts) - case .m2: - var _v = _t.anyUnique(type: MyGame_Example2_Monster.self) - anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m2) - default: break - } - switch _t.anyAmbiguousType { - case .m1: - var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self) - anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m1) - case .m2: - var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self) - anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m2) - case .m3: - var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self) - anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m3) - default: break - } - vectorOfEnums = [] - for index in 0..<_t.vectorOfEnumsCount { - vectorOfEnums.append(_t.vectorOfEnums(at: index)!) - } - signedEnum = _t.signedEnum - testrequirednestedflatbuffer = [] - for index in 0..<_t.testrequirednestedflatbufferCount { - testrequirednestedflatbuffer.append(_t.testrequirednestedflatbuffer(at: index)) - } + public init(_ _t: inout MyGame_Example_Monster) { + var __pos = _t.pos + pos = __pos?.unpack() + mana = _t.mana + hp = _t.hp + name = _t.name + inventory = [] + for index in 0..<_t.inventoryCount { + inventory.append(_t.inventory(at: index)) } - - public init() { - pos = MyGame_Example_Vec3T() - mana = 150 - hp = 100 - name = "" - inventory = [] - color = .blue - test4 = [] - testarrayofstring = [] - testarrayoftables = [] - enemy = MyGame_Example_MonsterT() - testnestedflatbuffer = [] - testempty = MyGame_Example_StatT() - testbool = false - testhashs32Fnv1 = 0 - testhashu32Fnv1 = 0 - testhashs64Fnv1 = 0 - testhashu64Fnv1 = 0 - testhashs32Fnv1a = 0 - testhashu32Fnv1a = 0 - testhashs64Fnv1a = 0 - testhashu64Fnv1a = 0 - testarrayofbools = [] - testf = 3.14159 - testf2 = 3.0 - testf3 = 0.0 - testarrayofstring2 = [] - testarrayofsortedstruct = [] - flex = [] - test5 = [] - vectorOfLongs = [] - vectorOfDoubles = [] - parentNamespaceTest = MyGame_InParentNamespaceT() - vectorOfReferrables = [] - singleWeakReference = 0 - vectorOfWeakReferences = [] - vectorOfStrongReferrables = [] - coOwningReference = 0 - vectorOfCoOwningReferences = [] - nonOwningReference = 0 - vectorOfNonOwningReferences = [] - vectorOfEnums = [] - signedEnum = .none_ - testrequirednestedflatbuffer = [] + color = _t.color + switch _t.testType { + case .monster: + var _v = _t.test(type: MyGame_Example_Monster.self) + test = MyGame_Example_Any_Union(_v?.unpack(), type: .monster) + case .testsimpletablewithenum: + var _v = _t.test(type: MyGame_Example_TestSimpleTableWithEnum.self) + test = MyGame_Example_Any_Union(_v?.unpack(), type: .testsimpletablewithenum) + case .mygameExample2Monster: + var _v = _t.test(type: MyGame_Example2_Monster.self) + test = MyGame_Example_Any_Union(_v?.unpack(), type: .mygameExample2Monster) + default: break } + test4 = [] + for index in 0..<_t.test4Count { + var __v_ = _t.test4(at: index) + test4.append(__v_?.unpack()) + } + testarrayofstring = [] + for index in 0..<_t.testarrayofstringCount { + testarrayofstring.append(_t.testarrayofstring(at: index)) + } + testarrayoftables = [] + for index in 0..<_t.testarrayoftablesCount { + var __v_ = _t.testarrayoftables(at: index) + testarrayoftables.append(__v_?.unpack()) + } + var __enemy = _t.enemy + enemy = __enemy?.unpack() + testnestedflatbuffer = [] + for index in 0..<_t.testnestedflatbufferCount { + testnestedflatbuffer.append(_t.testnestedflatbuffer(at: index)) + } + var __testempty = _t.testempty + testempty = __testempty?.unpack() + testbool = _t.testbool + testhashs32Fnv1 = _t.testhashs32Fnv1 + testhashu32Fnv1 = _t.testhashu32Fnv1 + testhashs64Fnv1 = _t.testhashs64Fnv1 + testhashu64Fnv1 = _t.testhashu64Fnv1 + testhashs32Fnv1a = _t.testhashs32Fnv1a + testhashu32Fnv1a = _t.testhashu32Fnv1a + testhashs64Fnv1a = _t.testhashs64Fnv1a + testhashu64Fnv1a = _t.testhashu64Fnv1a + testarrayofbools = [] + for index in 0..<_t.testarrayofboolsCount { + testarrayofbools.append(_t.testarrayofbools(at: index)) + } + testf = _t.testf + testf2 = _t.testf2 + testf3 = _t.testf3 + testarrayofstring2 = [] + for index in 0..<_t.testarrayofstring2Count { + testarrayofstring2.append(_t.testarrayofstring2(at: index)) + } + testarrayofsortedstruct = [] + for index in 0..<_t.testarrayofsortedstructCount { + var __v_ = _t.testarrayofsortedstruct(at: index) + testarrayofsortedstruct.append(__v_?.unpack()) + } + flex = [] + for index in 0..<_t.flexCount { + flex.append(_t.flex(at: index)) + } + test5 = [] + for index in 0..<_t.test5Count { + var __v_ = _t.test5(at: index) + test5.append(__v_?.unpack()) + } + vectorOfLongs = [] + for index in 0..<_t.vectorOfLongsCount { + vectorOfLongs.append(_t.vectorOfLongs(at: index)) + } + vectorOfDoubles = [] + for index in 0..<_t.vectorOfDoublesCount { + vectorOfDoubles.append(_t.vectorOfDoubles(at: index)) + } + var __parentNamespaceTest = _t.parentNamespaceTest + parentNamespaceTest = __parentNamespaceTest?.unpack() + vectorOfReferrables = [] + for index in 0..<_t.vectorOfReferrablesCount { + var __v_ = _t.vectorOfReferrables(at: index) + vectorOfReferrables.append(__v_?.unpack()) + } + singleWeakReference = _t.singleWeakReference + vectorOfWeakReferences = [] + for index in 0..<_t.vectorOfWeakReferencesCount { + vectorOfWeakReferences.append(_t.vectorOfWeakReferences(at: index)) + } + vectorOfStrongReferrables = [] + for index in 0..<_t.vectorOfStrongReferrablesCount { + var __v_ = _t.vectorOfStrongReferrables(at: index) + vectorOfStrongReferrables.append(__v_?.unpack()) + } + coOwningReference = _t.coOwningReference + vectorOfCoOwningReferences = [] + for index in 0..<_t.vectorOfCoOwningReferencesCount { + vectorOfCoOwningReferences.append(_t.vectorOfCoOwningReferences(at: index)) + } + nonOwningReference = _t.nonOwningReference + vectorOfNonOwningReferences = [] + for index in 0..<_t.vectorOfNonOwningReferencesCount { + vectorOfNonOwningReferences.append(_t.vectorOfNonOwningReferences(at: index)) + } + switch _t.anyUniqueType { + case .m: + var _v = _t.anyUnique(type: MyGame_Example_Monster.self) + anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m) + case .ts: + var _v = _t.anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self) + anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .ts) + case .m2: + var _v = _t.anyUnique(type: MyGame_Example2_Monster.self) + anyUnique = MyGame_Example_AnyUniqueAliasesUnion(_v?.unpack(), type: .m2) + default: break + } + switch _t.anyAmbiguousType { + case .m1: + var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self) + anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m1) + case .m2: + var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self) + anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m2) + case .m3: + var _v = _t.anyAmbiguous(type: MyGame_Example_Monster.self) + anyAmbiguous = MyGame_Example_AnyAmbiguousAliasesUnion(_v?.unpack(), type: .m3) + default: break + } + vectorOfEnums = [] + for index in 0..<_t.vectorOfEnumsCount { + vectorOfEnums.append(_t.vectorOfEnums(at: index)!) + } + signedEnum = _t.signedEnum + testrequirednestedflatbuffer = [] + for index in 0..<_t.testrequirednestedflatbufferCount { + testrequirednestedflatbuffer.append(_t.testrequirednestedflatbuffer(at: index)) + } + } - public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Monster.self) } + public init() { + pos = MyGame_Example_Vec3T() + mana = 150 + hp = 100 + name = "" + inventory = [] + color = .blue + test4 = [] + testarrayofstring = [] + testarrayoftables = [] + enemy = MyGame_Example_MonsterT() + testnestedflatbuffer = [] + testempty = MyGame_Example_StatT() + testbool = false + testhashs32Fnv1 = 0 + testhashu32Fnv1 = 0 + testhashs64Fnv1 = 0 + testhashu64Fnv1 = 0 + testhashs32Fnv1a = 0 + testhashu32Fnv1a = 0 + testhashs64Fnv1a = 0 + testhashu64Fnv1a = 0 + testarrayofbools = [] + testf = 3.14159 + testf2 = 3.0 + testf3 = 0.0 + testarrayofstring2 = [] + testarrayofsortedstruct = [] + flex = [] + test5 = [] + vectorOfLongs = [] + vectorOfDoubles = [] + parentNamespaceTest = MyGame_InParentNamespaceT() + vectorOfReferrables = [] + singleWeakReference = 0 + vectorOfWeakReferences = [] + vectorOfStrongReferrables = [] + coOwningReference = 0 + vectorOfCoOwningReferences = [] + nonOwningReference = 0 + vectorOfNonOwningReferences = [] + vectorOfEnums = [] + signedEnum = .none_ + testrequirednestedflatbuffer = [] + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Monster.self) } } public struct MyGame_Example_TypeAliases: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } - public static func getRootAsTypeAliases(bb: ByteBuffer) -> MyGame_Example_TypeAliases { return MyGame_Example_TypeAliases(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MONS", addPrefix: prefix) } + public static func getRootAsTypeAliases(bb: ByteBuffer) -> MyGame_Example_TypeAliases { return MyGame_Example_TypeAliases(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } - } + 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 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 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, - vectorOfV8 v8: Offset = Offset(), - vectorOfVf64 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 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 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 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, + vectorOfV8 v8: Offset = Offset(), + vectorOfVf64 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 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 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 class MyGame_Example_TypeAliasesT: NativeTable { - 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 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(_ _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)) } - - 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 = [] + vf64 = [] + for index in 0..<_t.vf64Count { + vf64.append(_t.vf64(at: index)) } + } - public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TypeAliases.self) } + 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/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift index 6098397ae..697eddefe 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift @@ -1,227 +1,228 @@ // automatically generated by the FlatBuffers compiler, do not modify // swiftlint:disable all +// swiftformat:disable all import FlatBuffers public enum optional_scalars_OptionalByte: Int8, Enum { - 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 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_ } + public static var max: optional_scalars_OptionalByte { return .two } + public static var min: optional_scalars_OptionalByte { return .none_ } } public struct optional_scalars_ScalarStuff: FlatBufferObject { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "NULL", addPrefix: prefix) } - public static func getRootAsScalarStuff(bb: ByteBuffer) -> optional_scalars_ScalarStuff { return optional_scalars_ScalarStuff(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "NULL", addPrefix: prefix) } + public static func getRootAsScalarStuff(bb: ByteBuffer) -> optional_scalars_ScalarStuff { return optional_scalars_ScalarStuff(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } - } + 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 : 0 != _accessor.readBuffer(of: Byte.self, at: o) } - public var maybeBool: Bool? { let o = _accessor.offset(VTOFFSET.maybeBool.v); return o == 0 ? true : 0 != _accessor.readBuffer(of: Byte.self, at: o) } - public var defaultBool: Bool { let o = _accessor.offset(VTOFFSET.defaultBool.v); return o == 0 ? true : 0 != _accessor.readBuffer(of: Byte.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 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 : 0 != _accessor.readBuffer(of: Byte.self, at: o) } + public var maybeBool: Bool? { let o = _accessor.offset(VTOFFSET.maybeBool.v); return o == 0 ? true : 0 != _accessor.readBuffer(of: Byte.self, at: o) } + public var defaultBool: Bool { let o = _accessor.offset(VTOFFSET.defaultBool.v); return o == 0 ? true : 0 != _accessor.readBuffer(of: Byte.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) + } } diff --git a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift index 10f244833..88cb4fb3b 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift @@ -1,336 +1,337 @@ // automatically generated by the FlatBuffers compiler, do not modify // swiftlint:disable all +// swiftformat:disable all import FlatBuffers public enum Character: UInt8, Enum { - public typealias T = UInt8 - 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 typealias T = UInt8 + 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_ } + public static var max: Character { return .unused } + public static var min: Character { return .none_ } } public struct CharacterUnion { - public var type: Character - public var value: NativeTable? - public init(_ v: NativeTable?, 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? RapunzelT - return Rapunzel.pack(&builder, obj: &__obj) - case .belle: - var __obj = value as? BookReaderT - return BookReader.pack(&builder, obj: &__obj) - case .bookfan: - var __obj = value as? BookReaderT - return BookReader.pack(&builder, obj: &__obj) - default: return Offset() - } + public var type: Character + public var value: NativeTable? + public init(_ v: NativeTable?, 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? RapunzelT + return Rapunzel.pack(&builder, obj: &__obj) + case .belle: + var __obj = value as? BookReaderT + return BookReader.pack(&builder, obj: &__obj) + case .bookfan: + var __obj = value as? BookReaderT + return BookReader.pack(&builder, obj: &__obj) + default: return Offset() } + } } public struct Rapunzel: Readable { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Struct + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct - public static var size = 4 - public static var alignment = 4 - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + public static var size = 4 + public static var alignment = 4 + 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 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() -> RapunzelT { - return RapunzelT(&self) - } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT?) -> Offset { - guard var obj = obj else { return Offset() } - return pack(&builder, obj: &obj) - } + public mutating func unpack() -> RapunzelT { + return RapunzelT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT) -> Offset { - return createRapunzel(builder: &builder, hairLength: obj.hairLength) - } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT) -> Offset { + return createRapunzel(builder: &builder, hairLength: obj.hairLength) + } } public class RapunzelT: NativeTable { - public var hairLength: Int32 + public var hairLength: Int32 - public init(_ _t: inout Rapunzel) { - hairLength = _t.hairLength - } + public init(_ _t: inout Rapunzel) { + hairLength = _t.hairLength + } - public init() { - hairLength = 0 - } + public init() { + hairLength = 0 + } } public struct BookReader: Readable { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Struct + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct - public static var size = 4 - public static var alignment = 4 - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + public static var size = 4 + public static var alignment = 4 + 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 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() -> BookReaderT { - return BookReaderT(&self) - } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT?) -> Offset { - guard var obj = obj else { return Offset() } - return pack(&builder, obj: &obj) - } + public mutating func unpack() -> BookReaderT { + return BookReaderT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } - public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT) -> Offset { - return createBookReader(builder: &builder, booksRead: obj.booksRead) - } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT) -> Offset { + return createBookReader(builder: &builder, booksRead: obj.booksRead) + } } public class BookReaderT: NativeTable { - public var booksRead: Int32 + public var booksRead: Int32 - public init(_ _t: inout BookReader) { - booksRead = _t.booksRead - } + public init(_ _t: inout BookReader) { + booksRead = _t.booksRead + } - public init() { - booksRead = 0 - } + public init() { + booksRead = 0 + } } extension Rapunzel { - @discardableResult - public static func createRapunzel(builder: inout FlatBufferBuilder, hairLength: Int32 = 0) -> Offset { - builder.createStructOf(size: Rapunzel.size, alignment: Rapunzel.alignment) - builder.reverseAdd(v: hairLength, postion: 0) - return builder.endStruct() - } + @discardableResult + public static func createRapunzel(builder: inout FlatBufferBuilder, hairLength: Int32 = 0) -> Offset { + builder.createStructOf(size: Rapunzel.size, alignment: Rapunzel.alignment) + builder.reverseAdd(v: hairLength, postion: 0) + return builder.endStruct() + } } extension BookReader { - @discardableResult - public static func createBookReader(builder: inout FlatBufferBuilder, booksRead: Int32 = 0) -> Offset { - builder.createStructOf(size: BookReader.size, alignment: BookReader.alignment) - builder.reverseAdd(v: booksRead, postion: 0) - return builder.endStruct() - } + @discardableResult + public static func createBookReader(builder: inout FlatBufferBuilder, booksRead: Int32 = 0) -> Offset { + builder.createStructOf(size: BookReader.size, alignment: BookReader.alignment) + builder.reverseAdd(v: booksRead, postion: 0) + return builder.endStruct() + } } public struct Attacker: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) } - public static func getRootAsAttacker(bb: ByteBuffer) -> Attacker { return Attacker(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) } + public static func getRootAsAttacker(bb: ByteBuffer) -> Attacker { return Attacker(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } - } + 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 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 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 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 class AttackerT: NativeTable { - public var swordAttackDamage: Int32 + public var swordAttackDamage: Int32 - public init(_ _t: inout Attacker) { - swordAttackDamage = _t.swordAttackDamage - } + public init(_ _t: inout Attacker) { + swordAttackDamage = _t.swordAttackDamage + } - public init() { - swordAttackDamage = 0 - } + public init() { + swordAttackDamage = 0 + } - public func serialize() -> ByteBuffer { return serialize(type: Attacker.self) } + public func serialize() -> ByteBuffer { return serialize(type: Attacker.self) } } public struct Movie: FlatBufferObject, ObjectAPI { - static func validateVersion() { FlatBuffersVersion_1_12_0() } - public var __buffer: ByteBuffer! { return _accessor.bb } - private var _accessor: Table + static func validateVersion() { FlatBuffersVersion_1_12_0() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table - public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) } - public static func getRootAsMovie(bb: ByteBuffer) -> Movie { return Movie(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) } + public static func getRootAsMovie(bb: ByteBuffer) -> Movie { return Movie(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) } - private init(_ t: Table) { _accessor = t } - public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + 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 } + 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 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 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_, + offsetOfMainCharacter mainCharacter: Offset = Offset(), + vectorOfCharactersType charactersType: Offset = Offset(), + vectorOfCharacters 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) } - 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 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 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_, - offsetOfMainCharacter mainCharacter: Offset = Offset(), - vectorOfCharactersType charactersType: Offset = Offset(), - vectorOfCharacters 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) - } + Movie.addVectorOf(charactersType: __charactersType, &builder) + Movie.addVectorOf(characters: __characters, &builder) + return Movie.endMovie(&builder, start: __root) + } } public class MovieT: NativeTable { - public var mainCharacter: CharacterUnion? - public var characters: [CharacterUnion?] + public var mainCharacter: CharacterUnion? + public var characters: [CharacterUnion?] - public init(_ _t: inout Movie) { - switch _t.mainCharacterType { + public init(_ _t: inout Movie) { + switch _t.mainCharacterType { + case .mulan: + var _v = _t.mainCharacter(type: Attacker.self) + mainCharacter = CharacterUnion(_v?.unpack(), type: .mulan) + case .rapunzel: + var _v = _t.mainCharacter(type: Rapunzel.self) + mainCharacter = CharacterUnion(_v?.unpack(), type: .rapunzel) + case .belle: + var _v = _t.mainCharacter(type: BookReader.self) + mainCharacter = CharacterUnion(_v?.unpack(), type: .belle) + case .bookfan: + var _v = _t.mainCharacter(type: BookReader.self) + mainCharacter = CharacterUnion(_v?.unpack(), type: .bookfan) + default: break + } + characters = [] + for index in 0..<_t.charactersCount { + switch _t.charactersType(at: index) { case .mulan: - var _v = _t.mainCharacter(type: Attacker.self) - mainCharacter = CharacterUnion(_v?.unpack(), type: .mulan) + var _v = _t.characters(at: index, type: Attacker.self) + characters.append(CharacterUnion(_v?.unpack(), type: .mulan)) case .rapunzel: - var _v = _t.mainCharacter(type: Rapunzel.self) - mainCharacter = CharacterUnion(_v?.unpack(), type: .rapunzel) + var _v = _t.characters(at: index, type: Rapunzel.self) + characters.append(CharacterUnion(_v?.unpack(), type: .rapunzel)) case .belle: - var _v = _t.mainCharacter(type: BookReader.self) - mainCharacter = CharacterUnion(_v?.unpack(), type: .belle) + var _v = _t.characters(at: index, type: BookReader.self) + characters.append(CharacterUnion(_v?.unpack(), type: .belle)) case .bookfan: - var _v = _t.mainCharacter(type: BookReader.self) - mainCharacter = CharacterUnion(_v?.unpack(), type: .bookfan) + var _v = _t.characters(at: index, type: BookReader.self) + characters.append(CharacterUnion(_v?.unpack(), type: .bookfan)) default: break } - characters = [] - for index in 0..<_t.charactersCount { - switch _t.charactersType(at: index) { - case .mulan: - var _v = _t.characters(at: index, type: Attacker.self) - characters.append(CharacterUnion(_v?.unpack(), type: .mulan)) - case .rapunzel: - var _v = _t.characters(at: index, type: Rapunzel.self) - characters.append(CharacterUnion(_v?.unpack(), type: .rapunzel)) - case .belle: - var _v = _t.characters(at: index, type: BookReader.self) - characters.append(CharacterUnion(_v?.unpack(), type: .belle)) - case .bookfan: - var _v = _t.characters(at: index, type: BookReader.self) - characters.append(CharacterUnion(_v?.unpack(), type: .bookfan)) - default: break - } - } } + } - public init() { - characters = [] - } + public init() { + characters = [] + } - public func serialize() -> ByteBuffer { return serialize(type: Movie.self) } + public func serialize() -> ByteBuffer { return serialize(type: Movie.self) } } diff --git a/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift b/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift index 1b16a78e7..68d7891fa 100644 --- a/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift +++ b/tests/FlatBuffers.Test.Swift/Tests/LinuxMain.swift @@ -1,3 +1,19 @@ +/* + * 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 XCTest import FlatBuffers_Test_SwiftTests