[Swift] Adds a format file and reformats the swift project (#6250)

* Formats files & adds licence

* Revert arrays

* Keeps array indentation as is

* Adds licence to code formatter

* Updates code generators
This commit is contained in:
mustiikhalil
2020-11-16 19:52:38 +03:00
committed by GitHub
parent 6764f25d91
commit 537212afee
39 changed files with 4975 additions and 4376 deletions

View File

@@ -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["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
vars["MethodName"] = method->name(); vars["MethodName"] = method->name();
vars["isNil"] = ""; vars["isNil"] = "";
printer->Print("\t"); printer->Print(" ");
auto func = GenerateClientFuncName(method.get()); auto func = GenerateClientFuncName(method.get());
printer->Print(vars, func.c_str()); printer->Print(vars, func.c_str());
printer->Print("\n"); printer->Print("\n");
@@ -115,15 +115,15 @@ void GenerateClientClass(const grpc_generator::Service *service,
printer->Print(vars, printer->Print(vars,
"$ACCESS$ final class $ServiceQualifiedName$ServiceClient: GRPCClient, " "$ACCESS$ final class $ServiceQualifiedName$ServiceClient: GRPCClient, "
"$ServiceQualifiedName$Service {\n"); "$ServiceQualifiedName$Service {\n");
printer->Print(vars, "\t$ACCESS$ let channel: GRPCChannel\n"); printer->Print(vars, " $ACCESS$ let channel: GRPCChannel\n");
printer->Print(vars, "\t$ACCESS$ var defaultCallOptions: CallOptions\n"); printer->Print(vars, " $ACCESS$ var defaultCallOptions: CallOptions\n");
printer->Print("\n"); printer->Print("\n");
printer->Print(vars, printer->Print(vars,
"\t$ACCESS$ init(channel: GRPCChannel, " " $ACCESS$ init(channel: GRPCChannel, "
"defaultCallOptions: CallOptions = CallOptions()) {\n"); "defaultCallOptions: CallOptions = CallOptions()) {\n");
printer->Print("\t\tself.channel = channel\n"); printer->Print(" self.channel = channel\n");
printer->Print("\t\tself.defaultCallOptions = defaultCallOptions\n"); printer->Print(" self.defaultCallOptions = defaultCallOptions\n");
printer->Print("\t}"); printer->Print(" }");
printer->Print("\n"); printer->Print("\n");
vars["GenAccess"] = service->is_internal() ? "internal" : "public"; vars["GenAccess"] = service->is_internal() ? "internal" : "public";
for (auto it = 0; it < service->method_count(); it++) { 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["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
vars["MethodName"] = method->name(); vars["MethodName"] = method->name();
vars["isNil"] = " = nil"; vars["isNil"] = " = nil";
printer->Print("\n\t"); printer->Print("\n ");
auto func = GenerateClientFuncName(method.get()); auto func = GenerateClientFuncName(method.get());
printer->Print(vars, func.c_str()); printer->Print(vars, func.c_str());
printer->Print(" {\n"); printer->Print(" {\n");
auto body = GenerateClientFuncBody(method.get()); auto body = GenerateClientFuncBody(method.get());
printer->Print("\t\t"); printer->Print(" ");
printer->Print(vars, body.c_str()); printer->Print(vars, body.c_str());
printer->Print("\n\t}\n"); printer->Print("\n }\n");
} }
printer->Print("}\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 GenerateServerExtensionBody(const grpc_generator::Method *method) {
grpc::string start = "\t\tcase \"$MethodName$\":\n\t\t"; grpc::string start = " case \"$MethodName$\":\n ";
if (method->NoStreaming()) { if (method->NoStreaming()) {
return start + return start +
"return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { " "return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { "
"context in" "context in"
"\n\t\t\t" "\n "
"return { request in" "return { request in"
"\n\t\t\t\t" "\n "
"self.$MethodName$(request, context: context)" "self.$MethodName$(request, context: context)"
"\n\t\t\t}" "\n }"
"\n\t\t}"; "\n }";
} }
if (method->ClientStreaming()) { if (method->ClientStreaming()) {
return start + return start +
"return CallHandlerFactory.makeClientStreaming(callHandlerContext: " "return CallHandlerFactory.makeClientStreaming(callHandlerContext: "
"callHandlerContext) { context in" "callHandlerContext) { context in"
"\n\t\t\t" "\n "
"self.$MethodName$(context: context)" "self.$MethodName$(context: context)"
"\n\t\t}"; "\n }";
} }
if (method->ServerStreaming()) { if (method->ServerStreaming()) {
return start + return start +
"return CallHandlerFactory.makeServerStreaming(callHandlerContext: " "return CallHandlerFactory.makeServerStreaming(callHandlerContext: "
"callHandlerContext) { context in" "callHandlerContext) { context in"
"\n\t\t\t" "\n "
"return { request in" "return { request in"
"\n\t\t\t\t" "\n "
"self.$MethodName$(request: request, context: context)" "self.$MethodName$(request: request, context: context)"
"\n\t\t\t}" "\n }"
"\n\t\t}"; "\n }";
} }
if (method->BidiStreaming()) { if (method->BidiStreaming()) {
return start + return start +
"return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: " "return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: "
"callHandlerContext) { context in" "callHandlerContext) { context in"
"\n\t\t\t" "\n "
"self.$MethodName$(context: context)" "self.$MethodName$(context: context)"
"\n\t\t}"; "\n }";
} }
return ""; 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["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["Output"] = GenerateMessage(method->get_output_namespace_parts(), method->get_output_type_name());
vars["MethodName"] = method->name(); vars["MethodName"] = method->name();
printer->Print("\t"); printer->Print(" ");
auto func = GenerateServerFuncName(method.get()); auto func = GenerateServerFuncName(method.get());
printer->Print(vars, func.c_str()); printer->Print(vars, func.c_str());
printer->Print("\n"); printer->Print("\n");
@@ -231,13 +231,13 @@ void GenerateServerProtocol(const grpc_generator::Service *service,
printer->Print(vars, "$ACCESS$ extension $ServiceQualifiedName$Provider {\n"); printer->Print(vars, "$ACCESS$ extension $ServiceQualifiedName$Provider {\n");
printer->Print("\n"); printer->Print("\n");
printer->Print(vars, printer->Print(vars,
"\tvar serviceName: Substring { return " " var serviceName: Substring { return "
"\"$PATH$$ServiceName$\" }\n"); "\"$PATH$$ServiceName$\" }\n");
printer->Print("\n"); printer->Print("\n");
printer->Print( printer->Print(
"\tfunc handleMethod(_ methodName: Substring, callHandlerContext: " " func handleMethod(_ methodName: Substring, callHandlerContext: "
"CallHandlerContext) -> GRPCCallHandler? {\n"); "CallHandlerContext) -> GRPCCallHandler? {\n");
printer->Print("\t\tswitch methodName {\n"); printer->Print(" switch methodName {\n");
for (auto it = 0; it < service->method_count(); it++) { for (auto it = 0; it < service->method_count(); it++) {
auto method = service->method(it); auto method = service->method(it);
vars["Input"] = GenerateMessage(method->get_input_namespace_parts(), method->get_input_type_name()); 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(vars, body.c_str());
printer->Print("\n"); printer->Print("\n");
} }
printer->Print("\t\tdefault: return nil;\n"); printer->Print(" default: return nil;\n");
printer->Print("\t\t}\n"); printer->Print(" }\n");
printer->Print("\t}\n\n"); printer->Print(" }\n\n");
printer->Print("}\n\n"); printer->Print("}");
} }
grpc::string Generate(grpc_generator::File *file, grpc::string Generate(grpc_generator::File *file,
@@ -281,6 +281,10 @@ grpc::string GenerateHeader() {
code += code +=
"/// in case of an issue please open github issue, though it would be " "/// in case of an issue please open github issue, though it would be "
"maintained\n"; "maintained\n";
code += "\n";
code += "// swiftlint:disable all\n";
code += "// swiftformat:disable all\n";
code += "\n";
code += "import Foundation\n"; code += "import Foundation\n";
code += "import GRPC\n"; code += "import GRPC\n";
code += "import NIO\n"; code += "import NIO\n";
@@ -292,19 +296,19 @@ grpc::string GenerateHeader() {
"{}\n"; "{}\n";
code += "public extension GRPCFlatBufPayload {\n"; code += "public extension GRPCFlatBufPayload {\n";
code += " init(serializedByteBuffer: inout NIO.ByteBuffer) throws {\n"; code += " init(serializedByteBuffer: inout NIO.ByteBuffer) throws {\n";
code += code +=
" self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: " " self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: "
"serializedByteBuffer.readableBytesView, count: " "serializedByteBuffer.readableBytesView, count: "
"serializedByteBuffer.readableBytes))\n"; "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 += code +=
" let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: " " let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: "
"Int(self.size))\n"; "Int(self.size))\n";
code += " buffer.writeBytes(buf)\n"; code += " buffer.writeBytes(buf)\n";
code += " }\n"; code += " }\n";
code += "}\n"; code += "}\n";
code += "extension Message: GRPCFlatBufPayload {}\n"; code += "extension Message: GRPCFlatBufPayload {}\n";
return code; return code;

View File

@@ -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 import FlatBuffers
typealias Monster = MyGame.Sample.Monster typealias Monster = MyGame.Sample.Monster
@@ -7,61 +22,62 @@ typealias Color = MyGame.Sample.Color
typealias Vec3 = MyGame.Sample.Vec3 typealias Vec3 = MyGame.Sample.Vec3
func main() { func main() {
let expectedDMG: [Int16] = [3, 5] let expectedDMG: [Int16] = [3, 5]
let expectedNames = ["Sword", "Axe"] let expectedNames = ["Sword", "Axe"]
var builder = FlatBufferBuilder(initialSize: 1024) var builder = FlatBufferBuilder(initialSize: 1024)
let weapon1Name = builder.create(string: expectedNames[0]) let weapon1Name = builder.create(string: expectedNames[0])
let weapon2Name = builder.create(string: expectedNames[1]) let weapon2Name = builder.create(string: expectedNames[1])
let weapon1Start = Weapon.startWeapon(&builder) let weapon1Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon1Name, &builder) Weapon.add(name: weapon1Name, &builder)
Weapon.add(damage: expectedDMG[0], &builder) Weapon.add(damage: expectedDMG[0], &builder)
let sword = Weapon.endWeapon(&builder, start: weapon1Start) let sword = Weapon.endWeapon(&builder, start: weapon1Start)
let weapon2Start = Weapon.startWeapon(&builder) let weapon2Start = Weapon.startWeapon(&builder)
Weapon.add(name: weapon2Name, &builder) Weapon.add(name: weapon2Name, &builder)
Weapon.add(damage: expectedDMG[1], &builder) Weapon.add(damage: expectedDMG[1], &builder)
let axe = Weapon.endWeapon(&builder, start: weapon2Start) let axe = Weapon.endWeapon(&builder, start: weapon2Start)
let name = builder.create(string: "Orc") let name = builder.create(string: "Orc")
let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let inventoryOffset = builder.createVector(inventory) let inventoryOffset = builder.createVector(inventory)
let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
let pos = MyGame.Sample.createVec3(x: 1, y: 2, z: 3) let pos = MyGame.Sample.createVec3(x: 1, y: 2, z: 3)
let orc = Monster.createMonster(&builder, let orc = Monster.createMonster(
structOfPos: pos, &builder,
hp: 300, structOfPos: pos,
offsetOfName: name, hp: 300,
vectorOfInventory: inventoryOffset, offsetOfName: name,
color: .red, vectorOfInventory: inventoryOffset,
vectorOfWeapons: weaponsOffset, color: .red,
equippedType: .weapon, vectorOfWeapons: weaponsOffset,
offsetOfEquipped: axe) equippedType: .weapon,
builder.finish(offset: orc) offsetOfEquipped: axe)
builder.finish(offset: orc)
let buf = builder.sizedByteArray let buf = builder.sizedByteArray
let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf)) let monster = Monster.getRootAsMonster(bb: ByteBuffer(bytes: buf))
assert(monster.mana == 150) assert(monster.mana == 150)
assert(monster.hp == 300) assert(monster.hp == 300)
assert(monster.name == "Orc") assert(monster.name == "Orc")
assert(monster.color == MyGame.Sample.Color.red) assert(monster.color == MyGame.Sample.Color.red)
assert(monster.pos != nil) assert(monster.pos != nil)
for i in 0..<monster.inventoryCount { for i in 0..<monster.inventoryCount {
assert(i == monster.inventory(at: i)) assert(i == monster.inventory(at: i))
} }
for i in 0..<monster.weaponsCount { for i in 0..<monster.weaponsCount {
let weap = monster.weapons(at: i) let weap = monster.weapons(at: i)
let index = Int(i) let index = Int(i)
assert(weap?.damage == expectedDMG[index]) assert(weap?.damage == expectedDMG[index])
assert(weap?.name == expectedNames[index]) assert(weap?.name == expectedNames[index])
} }
assert(monster.equippedType == .weapon) assert(monster.equippedType == .weapon)
let equipped = monster.equipped(type: Weapon.self) let equipped = monster.equipped(type: Weapon.self)
assert(equipped?.name == "Axe") assert(equipped?.name == "Axe")
assert(equipped?.damage == 5) assert(equipped?.damage == 5)
print("Monster Object is Verified") print("Monster Object is Verified")
} }

View File

@@ -47,7 +47,7 @@ class SwiftGenerator : public BaseGenerator {
const std::string &file_name) const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", "_", "swift") { : BaseGenerator(parser, path, file_name, "", "_", "swift") {
namespace_depth = 0; namespace_depth = 0;
code_.SetPadding(" "); code_.SetPadding(" ");
static const char *const keywords[] = { static const char *const keywords[] = {
"associatedtype", "associatedtype",
"class", "class",
@@ -137,7 +137,8 @@ class SwiftGenerator : public BaseGenerator {
code_.SetValue("ACCESS", "_accessor"); code_.SetValue("ACCESS", "_accessor");
code_.SetValue("TABLEOFFSET", "VTOFFSET"); code_.SetValue("TABLEOFFSET", "VTOFFSET");
code_ += "// " + std::string(FlatBuffersGeneratedWarning()); code_ += "// " + std::string(FlatBuffersGeneratedWarning());
code_ += "// swiftlint:disable all\n"; code_ += "// swiftlint:disable all";
code_ += "// swiftformat:disable all\n";
code_ += "import FlatBuffers\n"; code_ += "import FlatBuffers\n";
// Generate code for all the enum declarations. // Generate code for all the enum declarations.

26
swift.swiftformat Normal file
View File

@@ -0,0 +1,26 @@
--swiftversion 5.1
# format
--allman true
--indent 2
# options
--self remove # redundantSelf
--importgrouping testable-bottom # sortedImports
--trimwhitespace always
--indentcase false
--ifdef no-indent #indent
--wraparguments before-first # wrapArguments
--wrapparameters before-first # wrapArguments
--closingparen same-line # wrapArguments
--funcattributes prev-line # wrapAttributes
--typeattributes prev-line # wrapAttributes
# rules
--rules todos,anyObjectProtocol,redundantParens,redundantReturn,redundantSelf,sortedImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader
--disable trailingclosures
--exclude **/*_generated.swift
--exclude **/*.grpc.swift
--header "/*\n * Copyright {year} Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */"

View File

@@ -1,22 +1,35 @@
// swift-tools-version:5.2 // swift-tools-version:5.2
// 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 import PackageDescription
let package = Package( let package = Package(
name: "FlatBuffers", name: "FlatBuffers",
platforms: [ platforms: [
.iOS(.v11), .iOS(.v11),
.macOS(.v10_14), .macOS(.v10_14),
], ],
products: [ products: [
.library( .library(
name: "FlatBuffers", name: "FlatBuffers",
targets: ["FlatBuffers"]), targets: ["FlatBuffers"]),
], ],
targets: [ targets: [
.target( .target(
name: "FlatBuffers", name: "FlatBuffers",
dependencies: []), dependencies: []),
] ])
)

View File

@@ -1,345 +1,398 @@
/*
* 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 import Foundation
public struct ByteBuffer { public struct ByteBuffer {
/// Storage is a container that would hold the memory pointer to solve the issue of /// Storage is a container that would hold the memory pointer to solve the issue of
/// deallocating the memory that was held by (memory: UnsafeMutableRawPointer) /// deallocating the memory that was held by (memory: UnsafeMutableRawPointer)
@usableFromInline final class Storage { @usableFromInline
// This storage doesn't own the memory, therefore, we won't deallocate on deinit. final class Storage {
private let unowned: Bool // This storage doesn't own the memory, therefore, we won't deallocate on deinit.
/// pointer to the start of the buffer object in memory private let unowned: Bool
var memory: UnsafeMutableRawPointer /// pointer to the start of the buffer object in memory
/// Capacity of UInt8 the buffer can hold var memory: UnsafeMutableRawPointer
var capacity: Int /// Capacity of UInt8 the buffer can hold
var capacity: Int
init(count: Int, alignment: Int) { init(count: Int, alignment: Int) {
memory = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: alignment) memory = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: alignment)
capacity = count capacity = count
unowned = false unowned = false
}
init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) {
self.memory = memory
self.capacity = capacity
self.unowned = unowned
}
deinit {
if !unowned {
memory.deallocate()
}
}
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)
}
func initialize(for size: Int) {
assert(!unowned, "initalize should NOT be called on a buffer that is built by assumingMemoryBound")
memset(memory, 0, size)
}
/// Reallocates the buffer incase the object to be written doesnt fit in the current buffer
/// - Parameter size: Size of the current object
@usableFromInline internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
let currentWritingIndex = capacity &- writerSize
while capacity <= writerSize &+ size {
capacity = capacity << 1
}
/// solution take from Apple-NIO
capacity = capacity.convertToPowerofTwo
let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment)
memset(newData, 0, capacity &- writerSize)
memcpy(newData.advanced(by: capacity &- writerSize), memory.advanced(by: currentWritingIndex), writerSize)
memory.deallocate()
memory = newData
}
} }
@usableFromInline var _storage: Storage init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) {
self.memory = memory
/// The size of the elements written to the buffer + their paddings self.capacity = capacity
private var _writerSize: Int = 0 self.unowned = unowned
/// 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 { return _storage.capacity &- _writerSize }
/// Reader is the position of the current Writer Index (capacity - size)
public var reader: Int { return writerIndex }
/// Current size of the buffer
public var size: UOffset { return UOffset(_writerSize) }
/// Public Pointer to the buffer object in memory. This should NOT be modified for any reason
public var memory: UnsafeMutableRawPointer { return _storage.memory }
/// Current capacity for the buffer
public var capacity: Int { return _storage.capacity }
/// 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)
}
} }
/// Constructor that creates a Flatbuffer from the Swift Data type object deinit {
/// - Parameter data: Swift data Object if !unowned {
public init(data: Data) { memory.deallocate()
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)
}
} }
/// Constructor that creates a Flatbuffer instance with a size func copy(from ptr: UnsafeRawPointer, count: Int) {
/// - Parameter size: Length of the buffer assert(
init(initialSize size: Int) { !unowned,
let size = size.convertToPowerofTwo "copy should NOT be called on a buffer that is built by assumingMemoryBound")
_storage = Storage(count: size, alignment: alignment) memory.copyMemory(from: ptr, byteCount: count)
_storage.initialize(for: size)
} }
#if swift(>=5.0) func initialize(for size: Int) {
/// Constructor that creates a Flatbuffer object from a ContiguousBytes assert(
/// - Parameters: !unowned,
/// - contiguousBytes: Binary stripe to use as the buffer "initalize should NOT be called on a buffer that is built by assumingMemoryBound")
/// - count: amount of readable bytes memset(memory, 0, size)
public init<Bytes: ContiguousBytes>(
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
} }
/// Creates a copy of the buffer that's being built by calling sizedBuffer /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer
/// - Parameters: /// - Parameter size: Size of the current object
/// - memory: Current memory of the buffer @usableFromInline
/// - count: count of bytes internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
internal init(memory: UnsafeMutableRawPointer, count: Int) { let currentWritingIndex = capacity &- writerSize
_storage = Storage(count: count, alignment: alignment) while capacity <= writerSize &+ size {
_storage.copy(from: memory, count: count) capacity = capacity << 1
_writerSize = _storage.capacity }
}
/// Creates a copy of the existing flatbuffer, by copying it to a different memory. /// solution take from Apple-NIO
/// - Parameters: capacity = capacity.convertToPowerofTwo
/// - 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 let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment)
/// - Parameter padding: Amount of padding between two to be serialized objects memset(newData, 0, capacity &- writerSize)
@usableFromInline mutating func fill(padding: Int) { memcpy(
assert(padding >= 0, "Fill should be larger than or equal to zero") newData.advanced(by: capacity &- writerSize),
ensureSpace(size: padding) memory.advanced(by: currentWritingIndex),
_writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding) writerSize)
memory.deallocate()
memory = newData
} }
}
///Adds an array of type Scalar to the buffer memory @usableFromInline var _storage: Storage
/// - Parameter elements: An array of Scalars
@usableFromInline mutating func push<T: Scalar>(elements: [T]) {
let size = elements.count &* MemoryLayout<T>.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, /// The size of the elements written to the buffer + their paddings
/// - Parameters: private var _writerSize: Int = 0
/// - value: Pointer to the object in memory /// Aliginment of the current memory being written to the buffer
/// - size: Size of Value being written to the buffer internal var alignment = 1
@available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") /// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer
@usableFromInline mutating func push(struct value: UnsafeMutableRawPointer, size: Int) { internal var writerIndex: Int { _storage.capacity &- _writerSize }
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. /// Reader is the position of the current Writer Index (capacity - size)
/// The alignment of the memory is already handled since we already called preAlign public var reader: Int { writerIndex }
/// - Parameter size: size of the struct /// Current size of the buffer
@usableFromInline mutating func prepareBufferToReceiveStruct(of size: Int) { public var size: UOffset { UOffset(_writerSize) }
ensureSpace(size: size) /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason
_writerSize = _writerSize &+ size public var memory: UnsafeMutableRawPointer { _storage.memory }
} /// Current capacity for the buffer
public var capacity: Int { _storage.capacity }
/// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex` /// Constructor that creates a Flatbuffer object from a UInt8
/// and writes front to back into the buffer, respecting the padding & the alignment /// - Parameter bytes: Array of UInt8
/// - Parameters: public init(bytes: [UInt8]) {
/// - value: value of type Scalar var b = bytes
/// - position: position relative to the `writerIndex` _storage = Storage(count: bytes.count, alignment: alignment)
/// - len: length of the value in terms of bytes _writerSize = _storage.capacity
@usableFromInline mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) { b.withUnsafeMutableBytes { bufferPointer in
var v = value self._storage.copy(from: bufferPointer.baseAddress!, count: bytes.count)
memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len)
} }
}
/// Adds an object of type Scalar into the buffer /// Constructor that creates a Flatbuffer from the Swift Data type object
/// - Parameters: /// - Parameter data: Swift data Object
/// - value: Object that will be written to the buffer public init(data: Data) {
/// - len: Offset to subtract from the WriterIndex var b = data
@usableFromInline mutating func push<T: Scalar>(value: T, len: Int) { _storage = Storage(count: data.count, alignment: alignment)
ensureSpace(size: len) _writerSize = _storage.capacity
var v = value b.withUnsafeMutableBytes { bufferPointer in
memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len) self._storage.copy(from: bufferPointer.baseAddress!, count: data.count)
_writerSize = _writerSize &+ len
} }
}
/// Adds a string to the buffer using swift.utf8 object /// Constructor that creates a Flatbuffer instance with a size
/// - Parameter str: String that will be added to the buffer /// - Parameter size: Length of the buffer
/// - Parameter len: length of the string init(initialSize size: Int) {
@usableFromInline mutating func push(string str: String, len: Int) { let size = size.convertToPowerofTwo
ensureSpace(size: len) _storage = Storage(count: size, alignment: alignment)
if str.utf8.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != nil { _storage.initialize(for: size)
} else { }
let utf8View = str.utf8
for c in utf8View.reversed() {
push(value: c, len: 1)
}
}
}
/// Writes a string to Bytebuffer using UTF8View #if swift(>=5.0)
/// - Parameters: /// Constructor that creates a Flatbuffer object from a ContiguousBytes
/// - bytes: Pointer to the view /// - Parameters:
/// - len: Size of string /// - contiguousBytes: Binary stripe to use as the buffer
@usableFromInline mutating internal func push(bytes: UnsafeBufferPointer<String.UTF8View.Element>, len: Int) -> Bool { /// - count: amount of readable bytes
memcpy(_storage.memory.advanced(by: writerIndex &- len), UnsafeRawPointer(bytes.baseAddress!), len) public init<Bytes: ContiguousBytes>(
_writerSize = _writerSize &+ len contiguousBytes: Bytes,
return true count: Int)
{
_storage = Storage(count: count, alignment: alignment)
_writerSize = _storage.capacity
contiguousBytes.withUnsafeBytes { buf in
_storage.copy(from: buf.baseAddress!, count: buf.count)
} }
}
#endif
/// Write stores an object into the buffer directly or indirectly. /// Constructor that creates a Flatbuffer from unsafe memory region without copying
/// /// - Parameter assumingMemoryBound: The unsafe memory region
/// Direct: ignores the capacity of buffer which would mean we are referring to the direct point in memory /// - Parameter capacity: The size of the given memory region
/// indirect: takes into respect the current capacity of the buffer (capacity - index), writing to the buffer from the end public init(assumingMemoryBound memory: UnsafeMutableRawPointer, capacity: Int) {
/// - Parameters: _storage = Storage(memory: memory, capacity: capacity, unowned: true)
/// - value: Value that needs to be written to the buffer _writerSize = capacity
/// - index: index to write to }
/// - direct: Should take into consideration the capacity of the buffer
func write<T>(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 /// Creates a copy of the buffer that's being built by calling sizedBuffer
/// - Parameter size: size of object /// - Parameters:
@discardableResult /// - memory: Current memory of the buffer
@usableFromInline mutating func ensureSpace(size: Int) -> Int { /// - count: count of bytes
if size &+ _writerSize > _storage.capacity { internal init(memory: UnsafeMutableRawPointer, count: Int) {
_storage.reallocate(size, writerSize: _writerSize, alignment: alignment) _storage = Storage(count: count, alignment: alignment)
} _storage.copy(from: memory, count: count)
assert(size < FlatBufferMaxSize, "Buffer can't grow beyond 2 Gigabytes") _writerSize = _storage.capacity
return size }
}
/// pops the written VTable if it's already written into the buffer /// Creates a copy of the existing flatbuffer, by copying it to a different memory.
/// - Parameter size: size of the `VTable` /// - Parameters:
@usableFromInline mutating internal func pop(_ size: Int) { /// - memory: Current memory of the buffer
assert((_writerSize &- size) > 0, "New size should NOT be a negative number") /// - count: count of bytes
memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size) /// - removeBytes: Removes a number of bytes from the current size
_writerSize = size internal init(memory: UnsafeMutableRawPointer, count: Int, removing removeBytes: Int) {
} _storage = Storage(count: count, alignment: alignment)
_storage.copy(from: memory, count: count)
_writerSize = removeBytes
}
/// Clears the current size of the buffer /// Fills the buffer with padding by adding to the writersize
mutating public func clearSize() { /// - Parameter padding: Amount of padding between two to be serialized objects
_writerSize = 0 @usableFromInline
} mutating func fill(padding: Int) {
assert(padding >= 0, "Fill should be larger than or equal to zero")
ensureSpace(size: padding)
_writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding)
}
/// Clears the current instance of the buffer, replacing it with new memory ///Adds an array of type Scalar to the buffer memory
mutating public func clear() { /// - Parameter elements: An array of Scalars
_writerSize = 0 @usableFromInline
alignment = 1 mutating func push<T: Scalar>(elements: [T]) {
_storage.initialize(for: _storage.capacity) let size = elements.count &* MemoryLayout<T>.size
ensureSpace(size: size)
elements.reversed().forEach { s in
push(value: s, len: MemoryLayout.size(ofValue: s))
} }
}
/// Reads an object from the buffer /// A custom type of structs that are padded according to the flatbuffer padding,
/// - Parameters: /// - Parameters:
/// - def: Type of the object /// - value: Pointer to the object in memory
/// - position: the index of the object in the buffer /// - size: Size of Value being written to the buffer
public func read<T>(def: T.Type, position: Int) -> T { @available(
assert(position + MemoryLayout<T>.size <= _storage.capacity, "Reading out of bounds is illegal") *,
return _storage.memory.advanced(by: position).load(as: T.self) 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
}
/// Reads a slice from the memory assuming a type of T /// Prepares the buffer to receive a struct of certian size.
/// - Parameters: /// The alignment of the memory is already handled since we already called preAlign
/// - index: index of the object to be read from the buffer /// - Parameter size: size of the struct
/// - count: count of bytes in memory @usableFromInline
public func readSlice<T>(index: Int32, mutating func prepareBufferToReceiveStruct(of size: Int) {
count: Int32) -> [T] { ensureSpace(size: size)
let _index = Int(index) _writerSize = _writerSize &+ size
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 /// Reverse the input direction to the buffer, since `FlatBuffers` uses a back to front, following method will take current `writerIndex`
/// - Parameters: /// and writes front to back into the buffer, respecting the padding & the alignment
/// - index: index of the string in the buffer /// - Parameters:
/// - count: length of the string /// - value: value of type Scalar
/// - type: Encoding of the string /// - position: position relative to the `writerIndex`
public func readString(at index: Int32, /// - len: length of the value in terms of bytes
count: Int32, @usableFromInline
type: String.Encoding = .utf8) -> String? { mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) {
let _index = Int(index) var v = value
let _count = Int(count) memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len)
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 /// Adds an object of type Scalar into the buffer
/// - Parameter removeBytes: the amount of bytes to remove from the current Size /// - Parameters:
public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer { /// - value: Object that will be written to the buffer
assert(removeBytes > 0, "Can NOT remove negative bytes") /// - len: Offset to subtract from the WriterIndex
assert(removeBytes < _storage.capacity, "Can NOT remove more bytes than the ones allocated") @usableFromInline
return ByteBuffer(memory: _storage.memory, count: _storage.capacity, removing: _writerSize &- removeBytes) mutating func push<T: Scalar>(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<String.UTF8View.Element>,
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<T>(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<T>(def: T.Type, position: Int) -> T {
assert(
position + MemoryLayout<T>.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<T>(
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 { extension ByteBuffer: CustomDebugStringConvertible {
public var debugDescription: String { public var debugDescription: String {
""" """
buffer located at: \(_storage.memory), with capacity of \(_storage.capacity) buffer located at: \(_storage.memory), with capacity of \(_storage.capacity)
{ writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) } { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) }
""" """
} }
} }

View File

@@ -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) #if os(Linux)
import CoreFoundation import CoreFoundation
#else #else
@@ -20,77 +36,77 @@ public let FlatBufferMaxSize = UInt32.max << ((MemoryLayout<SOffset>.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. /// 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 { public protocol Scalar: Equatable {
associatedtype NumericValue associatedtype NumericValue
var convertedEndian: NumericValue { get } var convertedEndian: NumericValue { get }
} }
extension Scalar where Self: FixedWidthInteger { extension Scalar where Self: FixedWidthInteger {
/// Converts the value from BigEndian to LittleEndian /// Converts the value from BigEndian to LittleEndian
/// ///
/// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet. /// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet.
public var convertedEndian: NumericValue { public var convertedEndian: NumericValue {
return self as! Self.NumericValue self as! Self.NumericValue
} }
} }
extension Double: Scalar { extension Double: Scalar {
public typealias NumericValue = UInt64 public typealias NumericValue = UInt64
public var convertedEndian: UInt64 { public var convertedEndian: UInt64 {
return self.bitPattern.littleEndian bitPattern.littleEndian
} }
} }
extension Float32: Scalar { extension Float32: Scalar {
public typealias NumericValue = UInt32 public typealias NumericValue = UInt32
public var convertedEndian: UInt32 { public var convertedEndian: UInt32 {
return self.bitPattern.littleEndian bitPattern.littleEndian
} }
} }
extension Bool: Scalar { extension Bool: Scalar {
public var convertedEndian: UInt8 { public var convertedEndian: UInt8 {
return self == true ? 1 : 0 self == true ? 1 : 0
} }
public typealias NumericValue = UInt8 public typealias NumericValue = UInt8
} }
extension Int: Scalar { extension Int: Scalar {
public typealias NumericValue = Int public typealias NumericValue = Int
} }
extension Int8: Scalar { extension Int8: Scalar {
public typealias NumericValue = Int8 public typealias NumericValue = Int8
} }
extension Int16: Scalar { extension Int16: Scalar {
public typealias NumericValue = Int16 public typealias NumericValue = Int16
} }
extension Int32: Scalar { extension Int32: Scalar {
public typealias NumericValue = Int32 public typealias NumericValue = Int32
} }
extension Int64: Scalar { extension Int64: Scalar {
public typealias NumericValue = Int64 public typealias NumericValue = Int64
} }
extension UInt8: Scalar { extension UInt8: Scalar {
public typealias NumericValue = UInt8 public typealias NumericValue = UInt8
} }
extension UInt16: Scalar { extension UInt16: Scalar {
public typealias NumericValue = UInt16 public typealias NumericValue = UInt16
} }
extension UInt32: Scalar { extension UInt32: Scalar {
public typealias NumericValue = UInt32 public typealias NumericValue = UInt32
} }
extension UInt64: Scalar { extension UInt64: Scalar {
public typealias NumericValue = UInt64 public typealias NumericValue = UInt64
} }
public func FlatBuffersVersion_1_12_0() {} public func FlatBuffersVersion_1_12_0() {}

File diff suppressed because it is too large Load Diff

View File

@@ -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 import Foundation
/// FlatbufferObject structures all the Flatbuffers objects /// FlatbufferObject structures all the Flatbuffers objects
public protocol FlatBufferObject { public protocol FlatBufferObject {
var __buffer: ByteBuffer! { get } var __buffer: ByteBuffer! { get }
init(_ bb: ByteBuffer, o: Int32) init(_ bb: ByteBuffer, o: Int32)
} }
public protocol ObjectAPI { public protocol ObjectAPI {
associatedtype T associatedtype T
static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset<UOffset> static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset<UOffset>
mutating func unpack() -> T mutating func unpack() -> T
} }
/// Readable is structures all the Flatbuffers structs /// 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 /// 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 /// FlatBufferBuilder would require a Type to both create(struct:) and createVector(structs:) functions
public protocol Readable: FlatBufferObject { public protocol Readable: FlatBufferObject {
static var size: Int { get } static var size: Int { get }
static var alignment: Int { get } static var alignment: Int { get }
} }
public protocol Enum { public protocol Enum {
associatedtype T: Scalar associatedtype T: Scalar
static var byteSize: Int { get } static var byteSize: Int { get }
var value: T { get } var value: T { get }
} }

View File

@@ -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 import Foundation
public final class FlatBuffersUtils { public final class FlatBuffersUtils {
/// Gets the size of the prefix /// Gets the size of the prefix
/// - Parameter bb: Flatbuffer object /// - Parameter bb: Flatbuffer object
public static func getSizePrefix(bb: ByteBuffer) -> Int32 { public static func getSizePrefix(bb: ByteBuffer) -> Int32 {
return bb.read(def: Int32.self, position: bb.reader) bb.read(def: Int32.self, position: bb.reader)
} }
/// Removes the prefix by duplicating the Flatbuffer /// Removes the prefix by duplicating the Flatbuffer
/// - Parameter bb: Flatbuffer object /// - Parameter bb: Flatbuffer object
public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer { public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer {
return bb.duplicate(removing: MemoryLayout<Int32>.size) bb.duplicate(removing: MemoryLayout<Int32>.size)
} }
} }

View File

@@ -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 import Foundation
extension Int { extension Int {
/// Moves the current int into the nearest power of two /// Moves the current int into the nearest power of two
/// ///
/// This is used since the UnsafeMutableRawPointer will face issues when writing/reading /// This is used since the UnsafeMutableRawPointer will face issues when writing/reading
/// if the buffer alignment exceeds that actual size of the buffer /// if the buffer alignment exceeds that actual size of the buffer
var convertToPowerofTwo: Int { var convertToPowerofTwo: Int {
guard self > 0 else { return 1 } guard self > 0 else { return 1 }
var n = UOffset(self) var n = UOffset(self)
#if arch(arm) || arch(i386) #if arch(arm) || arch(i386)
let max = UInt32(Int.max) let max = UInt32(Int.max)
#else #else
let max = UInt32.max let max = UInt32.max
#endif #endif
n -= 1 n -= 1
n |= n >> 1 n |= n >> 1
n |= n >> 2 n |= n >> 2
n |= n >> 4 n |= n >> 4
n |= n >> 8 n |= n >> 8
n |= n >> 16 n |= n >> 16
if n != max { if n != max {
n += 1 n += 1
}
return Int(n)
} }
return Int(n)
}
} }

View File

@@ -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 { public protocol FlatBufferGRPCMessage {
/// Raw pointer which would be pointing to the beginning of the readable bytes /// Raw pointer which would be pointing to the beginning of the readable bytes
var rawPointer: UnsafeMutableRawPointer { get } var rawPointer: UnsafeMutableRawPointer { get }
/// Size of readable bytes in the buffer /// Size of readable bytes in the buffer
var size: Int { get } var size: Int { get }
init(byteBuffer: ByteBuffer) init(byteBuffer: ByteBuffer)
} }
/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the /// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the
/// GRPC library /// GRPC library
public final class Message<T: FlatBufferObject>: FlatBufferGRPCMessage { public final class Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
internal var buffer: ByteBuffer internal var buffer: ByteBuffer
/// Returns the an object of type T that would be read from the buffer /// Returns the an object of type T that would be read from the buffer
public var object: T { public var object: T {
T.init(buffer, o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) + Int32(buffer.reader)) 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 rawPointer: UnsafeMutableRawPointer { buffer.memory.advanced(by: buffer.reader) }
public var size: Int { return Int(buffer.size) } public var size: Int { Int(buffer.size) }
/// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over
/// GRPC /// GRPC
/// - Parameter byteBuffer: Flatbuffer ByteBuffer object /// - Parameter byteBuffer: Flatbuffer ByteBuffer object
public init(byteBuffer: ByteBuffer) { public init(byteBuffer: ByteBuffer) {
buffer = byteBuffer buffer = byteBuffer
} }
/// Initializes the message by copying the buffer to the message to be sent. /// Initializes the message by copying the buffer to the message to be sent.
/// from the builder /// from the builder
/// - Parameter builder: FlatbufferBuilder that has the bytes created in /// - Parameter builder: FlatbufferBuilder that has the bytes created in
/// - Note: Use `builder.finish(offset)` before passing the builder without prefixing anything to it /// - Note: Use `builder.finish(offset)` before passing the builder without prefixing anything to it
public init(builder: inout FlatBufferBuilder) { public init(builder: inout FlatBufferBuilder) {
buffer = builder.sizedBuffer buffer = builder.sizedBuffer
builder.clear() builder.clear()
} }
} }

View File

@@ -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 import Foundation
/// Mutable is a protocol that allows us to mutate Scalar values within the buffer /// Mutable is a protocol that allows us to mutate Scalar values within the buffer
public protocol Mutable { public protocol Mutable {
/// makes Flatbuffer accessed within the Protocol /// makes Flatbuffer accessed within the Protocol
var bb: ByteBuffer { get } var bb: ByteBuffer { get }
/// makes position of the table/struct accessed within the Protocol /// makes position of the table/struct accessed within the Protocol
var postion: Int32 { get } var postion: Int32 { get }
} }
extension Mutable { extension Mutable {
/// Mutates the memory in the buffer, this is only called from the access function of table and structs /// Mutates the memory in the buffer, this is only called from the access function of table and structs
/// - Parameters: /// - Parameters:
/// - value: New value to be inserted to the buffer /// - value: New value to be inserted to the buffer
/// - index: index of the Element /// - index: index of the Element
func mutate<T: Scalar>(value: T, o: Int32) -> Bool { func mutate<T: Scalar>(value: T, o: Int32) -> Bool {
guard o != 0 else { return false } guard o != 0 else { return false }
bb.write(value: value, index: Int(o), direct: true) bb.write(value: value, index: Int(o), direct: true)
return true return true
} }
} }
extension Mutable where Self == Table { extension Mutable where Self == Table {
/// Mutates a value by calling mutate with respect to the position in the table /// Mutates a value by calling mutate with respect to the position in the table
/// - Parameters: /// - Parameters:
/// - value: New value to be inserted to the buffer /// - value: New value to be inserted to the buffer
/// - index: index of the Element /// - index: index of the Element
public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool { public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
guard index != 0 else { return false } guard index != 0 else { return false }
return mutate(value: value, o: index + postion) return mutate(value: value, o: index + postion)
} }
/// Directly mutates the element by calling mutate /// Directly mutates the element by calling mutate
/// ///
/// Mutates the Element at index ignoring the current position by calling mutate /// Mutates the Element at index ignoring the current position by calling mutate
/// - Parameters: /// - Parameters:
/// - value: New value to be inserted to the buffer /// - value: New value to be inserted to the buffer
/// - index: index of the Element /// - index: index of the Element
public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool { public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
return mutate(value: value, o: index) mutate(value: value, o: index)
} }
} }
extension Mutable where Self == Struct { extension Mutable where Self == Struct {
/// Mutates a value by calling mutate with respect to the position in the struct /// Mutates a value by calling mutate with respect to the position in the struct
/// - Parameters: /// - Parameters:
/// - value: New value to be inserted to the buffer /// - value: New value to be inserted to the buffer
/// - index: index of the Element /// - index: index of the Element
public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool { public func mutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
return mutate(value: value, o: index + postion) mutate(value: value, o: index + postion)
} }
/// Directly mutates the element by calling mutate /// Directly mutates the element by calling mutate
/// ///
/// Mutates the Element at index ignoring the current position by calling mutate /// Mutates the Element at index ignoring the current position by calling mutate
/// - Parameters: /// - Parameters:
/// - value: New value to be inserted to the buffer /// - value: New value to be inserted to the buffer
/// - index: index of the Element /// - index: index of the Element
public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool { public func directMutate<T: Scalar>(_ value: T, index: Int32) -> Bool {
return mutate(value: value, o: index) mutate(value: value, o: index)
} }
} }
extension Struct: Mutable {} extension Struct: Mutable {}

View File

@@ -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 import Foundation
public protocol NativeTable {} public protocol NativeTable {}
extension NativeTable { extension NativeTable {
/// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th /// 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 /// - Parameter type: Type of the Flatbuffer object
/// - Returns: returns the encoded sized ByteBuffer /// - Returns: returns the encoded sized ByteBuffer
public func serialize<T: ObjectAPI>(type: T.Type) -> ByteBuffer where T.T == Self { public func serialize<T: ObjectAPI>(type: T.Type) -> ByteBuffer where T.T == Self {
var builder = FlatBufferBuilder(initialSize: 1024) var builder = FlatBufferBuilder(initialSize: 1024)
return serialize(builder: &builder, type: type.self) return serialize(builder: &builder, type: type.self)
} }
/// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly. /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
/// ///
/// - Parameters: /// - Parameters:
/// - builder: A FlatBufferBuilder /// - builder: A FlatBufferBuilder
/// - type: Type of the Flatbuffer object /// - type: Type of the Flatbuffer object
/// - Returns: returns the encoded sized ByteBuffer /// - 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`. /// - 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 /// It can be considered less expensive in terms of memory allocation
public func serialize<T: ObjectAPI>(builder: inout FlatBufferBuilder, type: T.Type) -> ByteBuffer where T.T == Self { public func serialize<T: ObjectAPI>(builder: inout FlatBufferBuilder, type: T.Type) -> ByteBuffer where T.T == Self {
var s = self var s = self
let root = type.pack(&builder, obj: &s) let root = type.pack(&builder, obj: &s)
builder.finish(offset: root) builder.finish(offset: root)
return builder.sizedBuffer return builder.sizedBuffer
} }
} }

View File

@@ -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 import Foundation
/// Offset object for all the Objects that are written into the buffer /// Offset object for all the Objects that are written into the buffer
public struct Offset<T> { public struct Offset<T> {
/// Offset of the object in the buffer /// Offset of the object in the buffer
public var o: UOffset public var o: UOffset
/// Returns false if the offset is equal to zero /// Returns false if the offset is equal to zero
public var isEmpty: Bool { return o == 0 } public var isEmpty: Bool { o == 0 }
public init(offset: UOffset) { o = offset } public init(offset: UOffset) { o = offset }
public init() { o = 0 } public init() { o = 0 }
} }

View File

@@ -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 import Foundation
public struct Struct { public struct Struct {
public private(set) var bb: ByteBuffer public private(set) var bb: ByteBuffer
public private(set) var postion: Int32 public private(set) var postion: Int32
public init(bb: ByteBuffer, position: Int32 = 0) { public init(bb: ByteBuffer, position: Int32 = 0) {
self.bb = bb self.bb = bb
self.postion = position postion = position
} }
public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T { public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
let r = bb.read(def: T.self, position: Int(o + postion)) let r = bb.read(def: T.self, position: Int(o + postion))
return r return r
} }
} }

View File

@@ -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 import Foundation
public struct Table { public struct Table {
public private(set) var bb: ByteBuffer public private(set) var bb: ByteBuffer
public private(set) var postion: Int32 public private(set) var postion: Int32
public init(bb: ByteBuffer, position: Int32 = 0) { public init(bb: ByteBuffer, position: Int32 = 0) {
guard isLitteEndian else { guard isLitteEndian else {
fatalError("Reading/Writing a buffer in big endian machine is not supported on swift") fatalError("Reading/Writing a buffer in big endian machine is not supported on swift")
}
self.bb = bb
self.postion = position
} }
self.bb = bb
postion = position
}
public func offset(_ o: Int32) -> Int32 { public func offset(_ o: Int32) -> Int32 {
let vtable = postion - bb.read(def: Int32.self, position: Int(postion)) 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 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 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. /// String reads from the buffer with respect to position of the current table.
/// - Parameter offset: Offset of the string /// - Parameter offset: Offset of the string
public func string(at offset: Int32) -> String? { public func string(at offset: Int32) -> String? {
return directString(at: offset + postion) directString(at: offset + postion)
} }
/// Direct string reads from the buffer disregarding the position of the table. /// 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 /// It would be preferable to use string unless the current position of the table is not needed
/// - Parameter offset: Offset of the string /// - Parameter offset: Offset of the string
public func directString(at offset: Int32) -> String? { public func directString(at offset: Int32) -> String? {
var offset = offset var offset = offset
offset += bb.read(def: Int32.self, position: Int(offset)) offset += bb.read(def: Int32.self, position: Int(offset))
let count = bb.read(def: Int32.self, position: Int(offset)) let count = bb.read(def: Int32.self, position: Int(offset))
let position = offset + Int32(MemoryLayout<Int32>.size) let position = offset + Int32(MemoryLayout<Int32>.size)
return bb.readString(at: position, count: count) return bb.readString(at: position, count: count)
} }
/// Reads from the buffer with respect to the position in the table. /// Reads from the buffer with respect to the position in the table.
/// - Parameters: /// - Parameters:
/// - type: Type of Scalar that needs to be read from the buffer /// - type: Type of Scalar that needs to be read from the buffer
/// - o: Offset of the Element /// - o: Offset of the Element
public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T { public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
return directRead(of: T.self, offset: o + postion) directRead(of: T.self, offset: o + postion)
} }
/// Reads from the buffer disregarding the position of the table. /// Reads from the buffer disregarding the position of the table.
/// It would be used when reading from an /// It would be used when reading from an
/// ``` /// ```
/// let offset = __t.offset(10) /// let offset = __t.offset(10)
/// //Only used when the we already know what is the /// //Only used when the we already know what is the
/// // position in the table since __t.vector(at:) /// // position in the table since __t.vector(at:)
/// // returns the index with respect to the position /// // returns the index with respect to the position
/// __t.directRead(of: Byte.self, /// __t.directRead(of: Byte.self,
/// offset: __t.vector(at: offset) + index * 1) /// offset: __t.vector(at: offset) + index * 1)
/// ``` /// ```
/// - Parameters: /// - Parameters:
/// - type: Type of Scalar that needs to be read from the buffer /// - type: Type of Scalar that needs to be read from the buffer
/// - o: Offset of the Element /// - o: Offset of the Element
public func directRead<T: Scalar>(of type: T.Type, offset o: Int32) -> T { public func directRead<T: Scalar>(of type: T.Type, offset o: Int32) -> T {
let r = bb.read(def: T.self, position: Int(o)) let r = bb.read(def: T.self, position: Int(o))
return r return r
} }
public func union<T: FlatBufferObject>(_ o: Int32) -> T { public func union<T: FlatBufferObject>(_ o: Int32) -> T {
let o = o + postion let o = o + postion
return directUnion(o) return directUnion(o)
} }
public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T { public func directUnion<T: FlatBufferObject>(_ o: Int32) -> T {
return T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o)))
} }
public func getVector<T>(at off: Int32) -> [T]? { public func getVector<T>(at off: Int32) -> [T]? {
let o = offset(off) let o = offset(off)
guard o != 0 else { return nil } guard o != 0 else { return nil }
return bb.readSlice(index: vector(at: o), count: vector(count: o)) return bb.readSlice(index: vector(at: o), count: vector(count: o))
} }
/// Vector count gets the count of Elements within the array /// Vector count gets the count of Elements within the array
/// - Parameter o: start offset of the vector /// - Parameter o: start offset of the vector
/// - returns: Count of elements /// - returns: Count of elements
public func vector(count o: Int32) -> Int32 { public func vector(count o: Int32) -> Int32 {
var o = o var o = o
o += postion o += postion
o += bb.read(def: Int32.self, position: Int(o)) o += bb.read(def: Int32.self, position: Int(o))
return bb.read(def: Int32.self, position: Int(o)) return bb.read(def: Int32.self, position: Int(o))
} }
/// Vector start index in the buffer /// Vector start index in the buffer
/// - Parameter o:start offset of the vector /// - Parameter o:start offset of the vector
/// - returns: the start index of the vector /// - returns: the start index of the vector
public func vector(at o: Int32) -> Int32 { public func vector(at o: Int32) -> Int32 {
var o = o var o = o
o += postion o += postion
return o + bb.read(def: Int32.self, position: Int(o)) + 4 return o + bb.read(def: Int32.self, position: Int(o)) + 4
} }
} }
extension Table { extension Table {
static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { return o + fbb.read(def: Int32.self, position: Int(o)) } 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 { static public func offset(_ o: Int32, vOffset: Int32, fbb: ByteBuffer) -> Int32 {
let vTable = Int32(fbb.capacity) - o 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))))) 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 { static public func compare(_ off1: Int32, _ off2: Int32, fbb: ByteBuffer) -> Int32 {
let memorySize = Int32(MemoryLayout<Int32>.size) let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2))
let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1))
let len2 = fbb.read(def: Int32.self, position: Int(_off2)) let len2 = fbb.read(def: Int32.self, position: Int(_off2))
let startPos1 = _off1 + memorySize let startPos1 = _off1 + memorySize
let startPos2 = _off2 + memorySize let startPos2 = _off2 + memorySize
let minValue = min(len1, len2) let minValue = min(len1, len2)
for i in 0...minValue { for i in 0...minValue {
let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1))
let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2))
if b1 != b2 { if b1 != b2 {
return Int32(b2 - b1) return Int32(b2 - b1)
} }
}
return len1 - len2
} }
return len1 - len2
}
static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 { static public func compare(_ off1: Int32, _ key: [Byte], fbb: ByteBuffer) -> Int32 {
let memorySize = Int32(MemoryLayout<Int32>.size) let memorySize = Int32(MemoryLayout<Int32>.size)
let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
let len1 = fbb.read(def: Int32.self, position: Int(_off1)) let len1 = fbb.read(def: Int32.self, position: Int(_off1))
let len2 = Int32(key.count) let len2 = Int32(key.count)
let startPos1 = _off1 + memorySize let startPos1 = _off1 + memorySize
let minValue = min(len1, len2) let minValue = min(len1, len2)
for i in 0..<minValue { for i in 0..<minValue {
let b = fbb.read(def: Int8.self, position: Int(i + startPos1)) let b = fbb.read(def: Int8.self, position: Int(i + startPos1))
let byte = key[Int(i)] let byte = key[Int(i)]
if b != byte { if b != byte {
return Int32(b - Int8(byte)) return Int32(b - Int8(byte))
} }
}
return len1 - len2
} }
return len1 - len2
}
} }

View File

@@ -1,19 +1,32 @@
// swift-tools-version:5.1 // 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 import PackageDescription
let package = Package( let package = Package(
name: "FlatBuffers.Benchmarks.swift", name: "FlatBuffers.Benchmarks.swift",
platforms: [ platforms: [
.macOS(.v10_14) .macOS(.v10_14),
], ],
dependencies: [ dependencies: [
.package(path: "../../swift") .package(path: "../../swift"),
], ],
targets: [ targets: [
.target( .target(
name: "FlatBuffers.Benchmarks.swift", name: "FlatBuffers.Benchmarks.swift",
dependencies: ["FlatBuffers"]), dependencies: ["FlatBuffers"]),
] ])
)

View File

@@ -1,104 +1,124 @@
/*
* 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 CoreFoundation import CoreFoundation
import FlatBuffers import FlatBuffers
struct Benchmark { struct Benchmark {
var name: String var name: String
var value: Double var value: Double
var description: String { "\(String(format: "|\t%@\t\t|\t\t%fs\t|", name, value))"} var description: String { "\(String(format: "|\t%@\t\t|\t\t%fs\t|", name, value))"}
} }
func run(name: String, runs: Int, action: () -> Void) -> Benchmark { func run(name: String, runs: Int, action: () -> Void) -> Benchmark {
action()
let start = CFAbsoluteTimeGetCurrent()
for _ in 0..<runs {
action() action()
let start = CFAbsoluteTimeGetCurrent() }
for _ in 0..<runs { let ends = CFAbsoluteTimeGetCurrent()
action() let value = Double(ends - start) / Double(runs)
} print("done \(name): in \(value)")
let ends = CFAbsoluteTimeGetCurrent() return Benchmark(name: name, value: value)
let value = Double(ends - start) / Double(runs)
print("done \(name): in \(value)")
return Benchmark(name: name, value: value)
} }
func createDocument(Benchmarks: [Benchmark]) -> String { func createDocument(Benchmarks: [Benchmark]) -> String {
let separator = "-------------------------------------" let separator = "-------------------------------------"
var document = "\(separator)\n" var document = "\(separator)\n"
document += "\(String(format: "|\t%@\t\t|\t\t%@\t\t|", "Name", "Scores"))\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" document += "\(separator)\n"
for i in Benchmarks { }
document += "\(i.description) \n" return document
document += "\(separator)\n"
}
return document
} }
@inlinable func create10Strings() { @inlinable
var fb = FlatBufferBuilder(initialSize: 1<<20) func create10Strings() {
for _ in 0..<10_000 { var fb = FlatBufferBuilder(initialSize: 1<<20)
_ = fb.create(string: "foobarbaz") for _ in 0..<10_000 {
} _ = fb.create(string: "foobarbaz")
}
} }
@inlinable func create100Strings(str: String) { @inlinable
var fb = FlatBufferBuilder(initialSize: 1<<20) func create100Strings(str: String) {
for _ in 0..<10_000 { var fb = FlatBufferBuilder(initialSize: 1<<20)
_ = fb.create(string: str) for _ in 0..<10_000 {
} _ = fb.create(string: str)
}
} }
@inlinable func benchmarkFiveHundredAdds() { @inlinable
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) func benchmarkFiveHundredAdds() {
for _ in 0..<500_000 { var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
let off = fb.create(string: "T") for _ in 0..<500_000 {
let s = fb.startTable(with: 4) let off = fb.create(string: "T")
fb.add(element: 3.2, def: 0, at: 2) let s = fb.startTable(with: 4)
fb.add(element: 4.2, def: 0, at: 4) fb.add(element: 3.2, def: 0, at: 2)
fb.add(element: 5.2, def: 0, at: 6) fb.add(element: 4.2, def: 0, at: 4)
fb.add(offset: off, at: 8) fb.add(element: 5.2, def: 0, at: 6)
_ = fb.endTable(at: s) fb.add(offset: off, at: 8)
} _ = fb.endTable(at: s)
}
} }
@inlinable func benchmarkThreeMillionStructs() { @inlinable
let structCount = 3_000_000 func benchmarkThreeMillionStructs() {
let structCount = 3_000_000
let rawSize = ((16 * 5) * structCount) / 1024 let rawSize = ((16 * 5) * structCount) / 1024
var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
var offsets: [Offset<UOffset>] = [] var offsets: [Offset<UOffset>] = []
for _ in 0..<structCount { for _ in 0..<structCount {
fb.startVectorOfStructs(count: 5, size: 16, alignment: 8) fb.startVectorOfStructs(count: 5, size: 16, alignment: 8)
for _ in 0..<5 { for _ in 0..<5 {
fb.createStructOf(size: 16, alignment: 8) fb.createStructOf(size: 16, alignment: 8)
fb.reverseAdd(v: 2.4, postion: 0) fb.reverseAdd(v: 2.4, postion: 0)
fb.reverseAdd(v: 2.4, postion: 8) fb.reverseAdd(v: 2.4, postion: 8)
fb.endStruct() fb.endStruct()
}
let vector = fb.endVectorOfStructs(count: 5)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
offsets.append(Offset<UOffset>(offset: fb.endTable(at: start)))
} }
let vector = fb.createVector(ofOffsets: offsets) let vector = fb.endVectorOfStructs(count: 5)
let start = fb.startTable(with: 1) let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4) fb.add(offset: vector, at: 4)
let root = Offset<UOffset>(offset: fb.endTable(at: start)) offsets.append(Offset<UOffset>(offset: fb.endTable(at: start)))
fb.finish(offset: root) }
let vector = fb.createVector(ofOffsets: offsets)
let start = fb.startTable(with: 1)
fb.add(offset: vector, at: 4)
let root = Offset<UOffset>(offset: fb.endTable(at: start))
fb.finish(offset: root)
} }
func benchmark(numberOfRuns runs: Int) { func benchmark(numberOfRuns runs: Int) {
var benchmarks: [Benchmark] = [] var benchmarks: [Benchmark] = []
let str = (0...99).map { _ -> String in return "x" }.joined() let str = (0...99).map { _ -> String in "x" }.joined()
benchmarks.append(run(name: "500_000", runs: runs, action: benchmarkFiveHundredAdds)) benchmarks.append(run(name: "500_000", runs: runs, action: benchmarkFiveHundredAdds))
benchmarks.append(run(name: "10 str", runs: runs, action: create10Strings)) benchmarks.append(run(name: "10 str", runs: runs, action: create10Strings))
let hundredStr = run(name: "100 str", runs: runs) { let hundredStr = run(name: "100 str", runs: runs) {
create100Strings(str: str) create100Strings(str: str)
} }
benchmarks.append(run(name: "3M strc", runs: 1, action: benchmarkThreeMillionStructs)) benchmarks.append(run(name: "3M strc", runs: 1, action: benchmarkThreeMillionStructs))
benchmarks.append(hundredStr) benchmarks.append(hundredStr)
print(createDocument(Benchmarks: benchmarks)) print(createDocument(Benchmarks: benchmarks))
} }
benchmark(numberOfRuns: 20) benchmark(numberOfRuns: 20)

View File

@@ -1,48 +1,58 @@
// swift-tools-version:5.1 // 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 import PackageDescription
let package = Package( let package = Package(
name: "FlatBuffers.GRPC.Swift", name: "FlatBuffers.GRPC.Swift",
platforms: [ platforms: [
.iOS(.v11), .iOS(.v11),
.macOS(.v10_14), .macOS(.v10_14),
], ],
dependencies: [ dependencies: [
.package(path: "../../swift"), .package(path: "../../swift"),
.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19") .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19"),
], ],
targets: [ targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite. // 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. // Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target( .target(
name: "Model", name: "Model",
dependencies: [ dependencies: [
"GRPC", "GRPC",
"FlatBuffers" "FlatBuffers",
], ],
path: "Sources/Model" path: "Sources/Model"),
),
// Client for the Greeter example // Client for the Greeter example
.target( .target(
name: "Client", name: "Client",
dependencies: [ dependencies: [
"GRPC", "GRPC",
"Model", "Model",
], ],
path: "Sources/client" path: "Sources/client"),
),
// Server for the Greeter example // Server for the Greeter example
.target( .target(
name: "Server", name: "Server",
dependencies: [ dependencies: [
"GRPC", "GRPC",
"Model", "Model",
], ],
path: "Sources/server" path: "Sources/server"),
), ])
]
)

View File

@@ -1,6 +1,10 @@
// Generated GRPC code for FlatBuffers swift! // Generated GRPC code for FlatBuffers swift!
/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-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 /// in case of an issue please open github issue, though it would be maintained
// swiftlint:disable all
// swiftformat:disable all
import Foundation import Foundation
import GRPC import GRPC
import NIO import NIO
@@ -9,67 +13,65 @@ import FlatBuffers
public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {} public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {}
public extension GRPCFlatBufPayload { public extension GRPCFlatBufPayload {
init(serializedByteBuffer: inout NIO.ByteBuffer) throws { init(serializedByteBuffer: inout NIO.ByteBuffer) throws {
self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes))
} }
func serialize(into buffer: inout NIO.ByteBuffer) throws { func serialize(into buffer: inout NIO.ByteBuffer) throws {
let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size)) let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size))
buffer.writeBytes(buf) buffer.writeBytes(buf)
} }
} }
extension Message: GRPCFlatBufPayload {} extension Message: GRPCFlatBufPayload {}
/// Usage: instantiate GreeterServiceClient, then call methods of this protocol to make API calls. /// Usage: instantiate GreeterServiceClient, then call methods of this protocol to make API calls.
public protocol GreeterService { public protocol GreeterService {
func SayHello(_ request: Message<HelloRequest>, callOptions: CallOptions?) -> UnaryCall<Message<HelloRequest>,Message<HelloReply>> func SayHello(_ request: Message<HelloRequest>, callOptions: CallOptions?) -> UnaryCall<Message<HelloRequest>,Message<HelloReply>>
func SayManyHellos(_ request: Message<ManyHellosRequest>, callOptions: CallOptions?, handler: @escaping (Message<HelloReply>) -> Void) -> ServerStreamingCall<Message<ManyHellosRequest>, Message<HelloReply>> func SayManyHellos(_ request: Message<ManyHellosRequest>, callOptions: CallOptions?, handler: @escaping (Message<HelloReply>) -> Void) -> ServerStreamingCall<Message<ManyHellosRequest>, Message<HelloReply>>
} }
public final class GreeterServiceClient: GRPCClient, GreeterService { public final class GreeterServiceClient: GRPCClient, GreeterService {
public let channel: GRPCChannel public let channel: GRPCChannel
public var defaultCallOptions: CallOptions public var defaultCallOptions: CallOptions
public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) {
self.channel = channel self.channel = channel
self.defaultCallOptions = defaultCallOptions self.defaultCallOptions = defaultCallOptions
} }
public func SayHello(_ request: Message<HelloRequest>, callOptions: CallOptions? = nil) -> UnaryCall<Message<HelloRequest>,Message<HelloReply>> { public func SayHello(_ request: Message<HelloRequest>, callOptions: CallOptions? = nil) -> UnaryCall<Message<HelloRequest>,Message<HelloReply>> {
return self.makeUnaryCall(path: "/Greeter/SayHello", request: request, callOptions: callOptions ?? self.defaultCallOptions) return self.makeUnaryCall(path: "/Greeter/SayHello", request: request, callOptions: callOptions ?? self.defaultCallOptions)
} }
public func SayManyHellos(_ request: Message<ManyHellosRequest>, callOptions: CallOptions? = nil, handler: @escaping (Message<HelloReply>) -> Void) -> ServerStreamingCall<Message<ManyHellosRequest>, Message<HelloReply>> { public func SayManyHellos(_ request: Message<ManyHellosRequest>, callOptions: CallOptions? = nil, handler: @escaping (Message<HelloReply>) -> Void) -> ServerStreamingCall<Message<ManyHellosRequest>, Message<HelloReply>> {
return self.makeServerStreamingCall(path: "/Greeter/SayManyHellos", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler) return self.makeServerStreamingCall(path: "/Greeter/SayManyHellos", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler)
} }
} }
public protocol GreeterProvider: CallHandlerProvider { public protocol GreeterProvider: CallHandlerProvider {
func SayHello(_ request: Message<HelloRequest>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<HelloReply>> func SayHello(_ request: Message<HelloRequest>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<HelloReply>>
func SayManyHellos(request: Message<ManyHellosRequest>, context: StreamingResponseCallContext<Message<HelloReply>>) -> EventLoopFuture<GRPCStatus> func SayManyHellos(request: Message<ManyHellosRequest>, context: StreamingResponseCallContext<Message<HelloReply>>) -> EventLoopFuture<GRPCStatus>
} }
public extension GreeterProvider { public extension GreeterProvider {
var serviceName: Substring { return "Greeter" } var serviceName: Substring { return "Greeter" }
func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? { func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
switch methodName { switch methodName {
case "SayHello": case "SayHello":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in return { request in
self.SayHello(request, context: context) self.SayHello(request, context: context)
} }
} }
case "SayManyHellos": case "SayManyHellos":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in return { request in
self.SayManyHellos(request: request, context: context) self.SayManyHellos(request: request, context: context)
} }
} }
default: return nil; default: return nil;
} }
} }
} }

View File

@@ -1,106 +1,107 @@
// automatically generated by the FlatBuffers compiler, do not modify // automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all // swiftlint:disable all
// swiftformat:disable all
import FlatBuffers import FlatBuffers
public struct HelloReply: FlatBufferObject { public struct HelloReply: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table 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 } private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset { private enum VTOFFSET: VOffset {
case message = 4 case message = 4
var v: Int32 { Int32(self.rawValue) } var v: Int32 { Int32(self.rawValue) }
var p: VOffset { 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 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 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 startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(message: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) } public static func add(message: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) }
public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createHelloReply( public static func createHelloReply(
_ fbb: inout FlatBufferBuilder, _ fbb: inout FlatBufferBuilder,
offsetOfMessage message: Offset<String> = Offset() offsetOfMessage message: Offset<String> = Offset()
) -> Offset<UOffset> { ) -> Offset<UOffset> {
let __start = HelloReply.startHelloReply(&fbb) let __start = HelloReply.startHelloReply(&fbb)
HelloReply.add(message: message, &fbb) HelloReply.add(message: message, &fbb)
return HelloReply.endHelloReply(&fbb, start: __start) return HelloReply.endHelloReply(&fbb, start: __start)
} }
} }
public struct HelloRequest: FlatBufferObject { public struct HelloRequest: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table 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 } private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset { private enum VTOFFSET: VOffset {
case name = 4 case name = 4
var v: Int32 { Int32(self.rawValue) } var v: Int32 { Int32(self.rawValue) }
var p: VOffset { 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 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 nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createHelloRequest( public static func createHelloRequest(
_ fbb: inout FlatBufferBuilder, _ fbb: inout FlatBufferBuilder,
offsetOfName name: Offset<String> = Offset() offsetOfName name: Offset<String> = Offset()
) -> Offset<UOffset> { ) -> Offset<UOffset> {
let __start = HelloRequest.startHelloRequest(&fbb) let __start = HelloRequest.startHelloRequest(&fbb)
HelloRequest.add(name: name, &fbb) HelloRequest.add(name: name, &fbb)
return HelloRequest.endHelloRequest(&fbb, start: __start) return HelloRequest.endHelloRequest(&fbb, start: __start)
} }
} }
public struct ManyHellosRequest: FlatBufferObject { public struct ManyHellosRequest: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table 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 } private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset { private enum VTOFFSET: VOffset {
case name = 4 case name = 4
case numGreetings = 6 case numGreetings = 6
var v: Int32 { Int32(self.rawValue) } var v: Int32 { Int32(self.rawValue) }
var p: VOffset { 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 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 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 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 startManyHellosRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
public static func add(name: Offset<String>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } public static func add(name: Offset<String>, _ 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 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<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } public static func endManyHellosRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createManyHellosRequest( public static func createManyHellosRequest(
_ fbb: inout FlatBufferBuilder, _ fbb: inout FlatBufferBuilder,
offsetOfName name: Offset<String> = Offset(), offsetOfName name: Offset<String> = Offset(),
numGreetings: Int32 = 0 numGreetings: Int32 = 0
) -> Offset<UOffset> { ) -> Offset<UOffset> {
let __start = ManyHellosRequest.startManyHellosRequest(&fbb) let __start = ManyHellosRequest.startManyHellosRequest(&fbb)
ManyHellosRequest.add(name: name, &fbb) ManyHellosRequest.add(name: name, &fbb)
ManyHellosRequest.add(numGreetings: numGreetings, &fbb) ManyHellosRequest.add(numGreetings: numGreetings, &fbb)
return ManyHellosRequest.endManyHellosRequest(&fbb, start: __start) return ManyHellosRequest.endManyHellosRequest(&fbb, start: __start)
} }
} }

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,88 +14,91 @@
* limitations under the License. * limitations under the License.
*/ */
import FlatBuffers
import GRPC import GRPC
import Logging
import Model import Model
import NIO import NIO
import Logging
import FlatBuffers
// Quieten the logs. // Quieten the logs.
LoggingSystem.bootstrap { LoggingSystem.bootstrap {
var handler = StreamLogHandler.standardOutput(label: $0) var handler = StreamLogHandler.standardOutput(label: $0)
handler.logLevel = .critical handler.logLevel = .critical
return handler return handler
} }
func greet(name: String, client greeter: GreeterServiceClient) { func greet(name: String, client greeter: GreeterServiceClient) {
// Form the request with the name, if one was provided. // Form the request with the name, if one was provided.
var builder = FlatBufferBuilder() var builder = FlatBufferBuilder()
let name = builder.create(string: name) let name = builder.create(string: name)
let root = HelloRequest.createHelloRequest(&builder, offsetOfName: name) let root = HelloRequest.createHelloRequest(&builder, offsetOfName: name)
builder.finish(offset: root) builder.finish(offset: root)
// Make the RPC call to the server. // Make the RPC call to the server.
let sayHello = greeter.SayHello(Message<HelloRequest>(builder: &builder)) let sayHello = greeter.SayHello(Message<HelloRequest>(builder: &builder))
// wait() on the response to stop the program from exiting before the response is received. // wait() on the response to stop the program from exiting before the response is received.
do { do {
let response = try sayHello.response.wait() let response = try sayHello.response.wait()
print("Greeter received: \(response.object.message)") print("Greeter received: \(response.object.message)")
} catch { } catch {
print("Greeter failed: \(error)") print("Greeter failed: \(error)")
} }
let surname = builder.create(string: "Name") let surname = builder.create(string: "Name")
let manyRoot = ManyHellosRequest.createManyHellosRequest(&builder, offsetOfName: surname, numGreetings: 2) let manyRoot = ManyHellosRequest.createManyHellosRequest(
builder.finish(offset: manyRoot) &builder,
offsetOfName: surname,
numGreetings: 2)
builder.finish(offset: manyRoot)
let call = greeter.SayManyHellos(Message(builder: &builder)) { message in let call = greeter.SayManyHellos(Message(builder: &builder)) { message in
print(message.object.message) print(message.object.message)
} }
let status = try! call.status.recover { _ in .processingError }.wait() let status = try! call.status.recover { _ in .processingError }.wait()
if status.code != .ok { if status.code != .ok {
print("RPC failed: \(status)") print("RPC failed: \(status)")
} }
} }
func main(args: [String]) { func main(args: [String]) {
// arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
// the name sent in the request. // the name sent in the request.
let arg1 = args.dropFirst(1).first let arg1 = args.dropFirst(1).first
let arg2 = args.dropFirst(2).first let arg2 = args.dropFirst(2).first
switch (arg1.flatMap(Int.init), arg2) { switch (arg1.flatMap(Int.init), arg2) {
case (.none, _): case (.none, _):
print("Usage: PORT [NAME]") print("Usage: PORT [NAME]")
exit(1) exit(1)
case let (.some(port), name): case let (.some(port), name):
// Setup an `EventLoopGroup` for the connection to run on. // Setup an `EventLoopGroup` for the connection to run on.
// //
// See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
// Make sure the group is shutdown when we're done with it. // Make sure the group is shutdown when we're done with it.
defer { defer {
try! group.syncShutdownGracefully() 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)
} }
// 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) main(args: CommandLine.arguments)

View File

@@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -14,50 +14,50 @@
* limitations under the License. * limitations under the License.
*/ */
import GRPC
import NIO
import FlatBuffers import FlatBuffers
import GRPC
import Logging import Logging
import Model import Model
import NIO
class Greeter: GreeterProvider { class Greeter: GreeterProvider {
var hellos: [Message<HelloReply>] = [] var hellos: [Message<HelloReply>] = []
init() { init() {
let names = ["Stranger1", "Stranger2", "Stranger4", "Stranger3", "Stranger5", "Stranger6"] let names = ["Stranger1", "Stranger2", "Stranger4", "Stranger3", "Stranger5", "Stranger6"]
for name in names { for name in names {
var builder = FlatBufferBuilder() var builder = FlatBufferBuilder()
let off = builder.create(string: name) let off = builder.create(string: name)
let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off) let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off)
builder.finish(offset: root) builder.finish(offset: root)
hellos.append(Message(builder: &builder)) hellos.append(Message(builder: &builder))
}
} }
}
func SayHello( func SayHello(
_ request: Message<HelloRequest>, _ request: Message<HelloRequest>,
context: StatusOnlyCallContext context: StatusOnlyCallContext) -> EventLoopFuture<Message<HelloReply>>
) -> EventLoopFuture<Message<HelloReply>> { {
let recipient = request.object.name ?? "Stranger" let recipient = request.object.name ?? "Stranger"
var builder = FlatBufferBuilder() var builder = FlatBufferBuilder()
let off = builder.create(string: recipient) let off = builder.create(string: recipient)
let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off) let root = HelloReply.createHelloReply(&builder, offsetOfMessage: off)
builder.finish(offset: root) builder.finish(offset: root)
return context.eventLoop.makeSucceededFuture(Message<HelloReply>(builder: &builder)) return context.eventLoop.makeSucceededFuture(Message<HelloReply>(builder: &builder))
} }
func SayManyHellos( func SayManyHellos(
request: Message<ManyHellosRequest>, request: Message<ManyHellosRequest>,
context: StreamingResponseCallContext<Message<HelloReply>> context: StreamingResponseCallContext<Message<HelloReply>>) -> EventLoopFuture<GRPCStatus>
) -> EventLoopFuture<GRPCStatus> { {
for _ in 0..<Int(request.object.numGreetings) { for _ in 0..<Int(request.object.numGreetings) {
let index = Int.random(in: 0..<hellos.count) let index = Int.random(in: 0..<hellos.count)
_ = context.sendResponse(hellos[index]) _ = context.sendResponse(hellos[index])
}
return context.eventLoop.makeSucceededFuture(.ok)
} }
return context.eventLoop.makeSucceededFuture(.ok)
}
} }
// Quieten the logs. // Quieten the logs.
@@ -76,8 +76,7 @@ defer {
let configuration = Server.Configuration( let configuration = Server.Configuration(
target: .hostAndPort("localhost", 0), target: .hostAndPort("localhost", 0),
eventLoopGroup: group, eventLoopGroup: group,
serviceProviders: [Greeter()] serviceProviders: [Greeter()])
)
// Start the server and print its address once it has started. // Start the server and print its address once it has started.
let server = Server.start(configuration: configuration) let server = Server.start(configuration: configuration)

View File

@@ -1,22 +1,35 @@
// swift-tools-version:5.1 // 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 import PackageDescription
let package = Package( let package = Package(
name: "FlatBuffers.Test.Swift", name: "FlatBuffers.Test.Swift",
platforms: [ platforms: [
.iOS(.v11), .iOS(.v11),
.macOS(.v10_14), .macOS(.v10_14),
], ],
dependencies: [ dependencies: [
.package(path: "../../swift/"), .package(path: "../../swift/"),
.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19") .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.0.0-alpha.19"),
], ],
targets: [ targets: [
.target(name: "SwiftFlatBuffers"), .target(name: "SwiftFlatBuffers"),
.testTarget( .testTarget(
name: "FlatBuffers.Test.SwiftTests", name: "FlatBuffers.Test.SwiftTests",
dependencies: ["FlatBuffers", "GRPC"]), dependencies: ["FlatBuffers", "GRPC"]),
] ])
)

View File

@@ -1,2 +1,18 @@
/*
* 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 import Foundation
print("Flatbuffers") print("Flatbuffers")

View File

@@ -1,10 +1,15 @@
swift_dir=`pwd` swift_dir=`pwd`
cd .. cd ..
test_dir=`pwd` test_dir=`pwd`
alias fbc='${test_dir}/../debug/flatc'
cd FlatBuffers.GRPC.Swift/Sources/Model
fbc --swift --grpc greeter.fbs
cd ${test_dir}
cd ${swift_dir}/Tests/FlatBuffers.Test.SwiftTests cd ${swift_dir}/Tests/FlatBuffers.Test.SwiftTests
${test_dir}/../flatc --swift --gen-mutable --grpc --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs ${test_dir}/union_vector/union_vector.fbs fbc --swift --gen-mutable --grpc --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs ${test_dir}/union_vector/union_vector.fbs
${test_dir}/../flatc --swift ${test_dir}/optional_scalars.fbs fbc --swift ${test_dir}/optional_scalars.fbs
cd ${swift_dir} cd ${swift_dir}
swift build --build-tests swift build --build-tests
swift test swift test

View File

@@ -1,5 +1,21 @@
import XCTest /*
* 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 import Foundation
import XCTest
@testable import FlatBuffers @testable import FlatBuffers
typealias Test = MyGame_Example_Test typealias Test = MyGame_Example_Test
@@ -9,274 +25,274 @@ typealias Stat = MyGame_Example_Stat
class FlatBuffersMonsterWriterTests: XCTestCase { class FlatBuffersMonsterWriterTests: XCTestCase {
func testData() { func testData() {
let data = Data([48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) let data = Data([48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0])
let _data = ByteBuffer(data: data) let _data = ByteBuffer(data: data)
readMonster(fb: _data) readMonster(fb: _data)
}
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)
}
func testCreateMonsterUsingCreateMonsterMethodWithNilPos() {
var fbb = FlatBufferBuilder(initialSize: 1)
let name = fbb.create(string: "Frodo")
let mStart = Monster.startMonster(&fbb)
Monster.add(name: name, &fbb)
let root = Monster.endMonster(&fbb, start: mStart)
fbb.finish(offset: root)
let newMonster = Monster.getRootAsMonster(bb: fbb.sizedBuffer)
XCTAssertNil(newMonster.pos)
XCTAssertEqual(newMonster.name, "Frodo")
}
func testCreateMonsterUsingCreateMonsterMethodWithPosX() {
var fbb = FlatBufferBuilder(initialSize: 1)
let name = fbb.create(string: "Barney")
let mStart = Monster.startMonster(&fbb)
Monster.add(pos: MyGame_Example_Vec3.createVec3(builder: &fbb, x: 10, test2: .blue), &fbb)
Monster.add(name: name, &fbb)
let root = Monster.endMonster(&fbb, start: mStart)
fbb.finish(offset: root)
let newMonster = Monster.getRootAsMonster(bb: fbb.sizedBuffer)
XCTAssertEqual(newMonster.pos!.x, 10)
XCTAssertEqual(newMonster.name, "Barney")
}
func testReadMonsterFromUnsafePointerWithoutCopying() {
var array: [UInt8] = [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]
let unpacked = array.withUnsafeMutableBytes { (memory) -> 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 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<UOffset>] = []
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..<monster.inventoryCount {
XCTAssertEqual(monster.inventory(at: i), Byte(i + 1))
} }
func testReadFromOtherLanguages() { XCTAssertEqual(monster.mutate(inventory: 0, at: 0), true)
let path = FileManager.default.currentDirectoryPath XCTAssertEqual(monster.mutate(inventory: 1, at: 1), true)
let url = URL(fileURLWithPath: path, isDirectory: true).appendingPathComponent("monsterdata_test").appendingPathExtension("mon") XCTAssertEqual(monster.mutate(inventory: 2, at: 2), true)
guard let data = try? Data(contentsOf: url) else { return } XCTAssertEqual(monster.mutate(inventory: 3, at: 3), true)
let _data = ByteBuffer(data: data) XCTAssertEqual(monster.mutate(inventory: 4, at: 4), true)
readMonster(fb: _data)
let vec = monster.pos
XCTAssertEqual(vec?.x, 1)
XCTAssertTrue(vec?.mutate(x: 55.0) ?? false)
XCTAssertTrue(vec?.mutate(test1: 55) ?? false)
XCTAssertEqual(vec?.x, 55.0)
XCTAssertEqual(vec?.test1, 55.0)
XCTAssertTrue(vec?.mutate(x: 1) ?? false)
XCTAssertEqual(vec?.x, 1)
XCTAssertTrue(vec?.mutate(test1: 3) ?? false)
}
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)
} }
XCTAssertEqual(sum, 10)
func testCreateMonster() { XCTAssertEqual(monster.test4Count, 2)
let bytes = createMonster(withPrefix: false) let test0 = monster.test4(at: 0)
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]) let test1 = monster.test4(at: 1)
readMonster(fb: bytes.buffer) var sum0 = 0
mutateMonster(fb: bytes.buffer) var sum1 = 0
readMonster(fb: bytes.buffer) if let a = test0?.a, let b = test0?.b {
sum0 = Int(a) + Int(b)
} }
if let a = test1?.a, let b = test1?.b {
func testCreateMonsterResizedBuffer() { sum1 = Int(a) + Int(b)
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)
} }
XCTAssertEqual(sum0 + sum1, 100)
XCTAssertEqual(monster.testarrayofstringCount, 2)
XCTAssertEqual(monster.testarrayofstring(at: 0), "test1")
XCTAssertEqual(monster.testarrayofstring(at: 1), "test2")
XCTAssertEqual(monster.testbool, true)
func testCreateMonsterPrefixed() { let array = monster.nameSegmentArray
let bytes = createMonster(withPrefix: true) XCTAssertEqual(String(bytes: array ?? [], encoding: .utf8), "MyMonster")
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) if 0 == monster.testarrayofboolsCount {
readMonster(fb: newBuf) XCTAssertEqual(monster.testarrayofbools.isEmpty, true)
} else {
XCTAssertEqual(monster.testarrayofbools.isEmpty, false)
} }
}
func testCreateMonsterUsingCreateMonsterMethodWithNilPos() { func readObjectApi(monster: MyGame_Example_MonsterT) {
var fbb = FlatBufferBuilder(initialSize: 1) XCTAssertEqual(monster.hp, 80)
let name = fbb.create(string: "Frodo") XCTAssertEqual(monster.mana, 150)
let mStart = Monster.startMonster(&fbb) XCTAssertEqual(monster.name, "MyMonster")
Monster.add(name: name, &fbb) let pos = monster.pos
let root = Monster.endMonster(&fbb, start: mStart) XCTAssertEqual(pos?.x, 1)
fbb.finish(offset: root) XCTAssertEqual(pos?.y, 2)
let newMonster = Monster.getRootAsMonster(bb: fbb.sizedBuffer) XCTAssertEqual(pos?.z, 3)
XCTAssertNil(newMonster.pos) XCTAssertEqual(pos?.test1, 3)
XCTAssertEqual(newMonster.name, "Frodo") XCTAssertEqual(pos?.test2, .green)
let test = pos?.test3
XCTAssertEqual(test?.a, 5)
XCTAssertEqual(test?.b, 6)
let monster2 = monster.test?.value as? MyGame_Example_MonsterT
XCTAssertEqual(monster2?.name, "Fred")
XCTAssertEqual(monster.mana, 150)
monster.mana = 10
XCTAssertEqual(monster.mana, 10)
monster.mana = 150
XCTAssertEqual(monster.mana, 150)
XCTAssertEqual(monster.inventory.count, 5)
var sum: Byte = 0
for i in monster.inventory {
sum += i
} }
XCTAssertEqual(sum, 10)
func testCreateMonsterUsingCreateMonsterMethodWithPosX() { XCTAssertEqual(monster.test4.count, 2)
var fbb = FlatBufferBuilder(initialSize: 1) let test0 = monster.test4[0]
let name = fbb.create(string: "Barney") let test1 = monster.test4[1]
let mStart = Monster.startMonster(&fbb) var sum0 = 0
Monster.add(pos: MyGame_Example_Vec3.createVec3(builder: &fbb, x: 10, test2: .blue), &fbb) var sum1 = 0
Monster.add(name: name, &fbb) if let a = test0?.a, let b = test0?.b {
let root = Monster.endMonster(&fbb, start: mStart) sum0 = Int(a) + Int(b)
fbb.finish(offset: root)
let newMonster = Monster.getRootAsMonster(bb: fbb.sizedBuffer)
XCTAssertEqual(newMonster.pos!.x, 10)
XCTAssertEqual(newMonster.name, "Barney")
} }
if let a = test1?.a, let b = test1?.b {
func testReadMonsterFromUnsafePointerWithoutCopying() { sum1 = Int(a) + Int(b)
var array: [UInt8] = [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]
let unpacked = array.withUnsafeMutableBytes { (memory) -> 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 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<UOffset>] = []
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..<monster.inventoryCount {
XCTAssertEqual(monster.inventory(at: i), Byte(i + 1))
}
XCTAssertEqual(monster.mutate(inventory: 0, at: 0), true)
XCTAssertEqual(monster.mutate(inventory: 1, at: 1), true)
XCTAssertEqual(monster.mutate(inventory: 2, at: 2), true)
XCTAssertEqual(monster.mutate(inventory: 3, at: 3), true)
XCTAssertEqual(monster.mutate(inventory: 4, at: 4), true)
let vec = monster.pos
XCTAssertEqual(vec?.x, 1)
XCTAssertTrue(vec?.mutate(x: 55.0) ?? false)
XCTAssertTrue(vec?.mutate(test1: 55) ?? false)
XCTAssertEqual(vec?.x, 55.0)
XCTAssertEqual(vec?.test1, 55.0)
XCTAssertTrue(vec?.mutate(x: 1) ?? false)
XCTAssertEqual(vec?.x, 1)
XCTAssertTrue(vec?.mutate(test1: 3) ?? false)
}
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)
}
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)
}
if let a = test1?.a, let b = test1?.b {
sum1 = Int(a) + Int(b)
}
XCTAssertEqual(sum0 + sum1, 100)
XCTAssertEqual(monster.testarrayofstringCount, 2)
XCTAssertEqual(monster.testarrayofstring(at: 0), "test1")
XCTAssertEqual(monster.testarrayofstring(at: 1), "test2")
XCTAssertEqual(monster.testbool, true)
let array = monster.nameSegmentArray
XCTAssertEqual(String(bytes: array ?? [], encoding: .utf8), "MyMonster")
if 0 == monster.testarrayofboolsCount {
XCTAssertEqual(monster.testarrayofbools.isEmpty, true)
} else {
XCTAssertEqual(monster.testarrayofbools.isEmpty, false)
}
}
func readObjectApi(monster: MyGame_Example_MonsterT) {
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)
let monster2 = monster.test?.value as? MyGame_Example_MonsterT
XCTAssertEqual(monster2?.name, "Fred")
XCTAssertEqual(monster.mana, 150)
monster.mana = 10
XCTAssertEqual(monster.mana, 10)
monster.mana = 150
XCTAssertEqual(monster.mana, 150)
XCTAssertEqual(monster.inventory.count, 5)
var sum: Byte = 0
for i in monster.inventory {
sum += i
}
XCTAssertEqual(sum, 10)
XCTAssertEqual(monster.test4.count, 2)
let test0 = monster.test4[0]
let test1 = monster.test4[1]
var sum0 = 0
var sum1 = 0
if let a = test0?.a, let b = test0?.b {
sum0 = Int(a) + Int(b)
}
if let a = test1?.a, let b = test1?.b {
sum1 = Int(a) + Int(b)
}
XCTAssertEqual(sum0 + sum1, 100)
XCTAssertEqual(monster.testbool, true)
} }
XCTAssertEqual(sum0 + sum1, 100)
XCTAssertEqual(monster.testbool, true)
}
} }

View File

@@ -1,43 +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.
*/
import XCTest import XCTest
@testable import FlatBuffers @testable import FlatBuffers
final class FlatBuffersStructsTests: XCTestCase { final class FlatBuffersStructsTests: XCTestCase {
func testWritingAndMutatingBools() { func testWritingAndMutatingBools() {
var fbb = FlatBufferBuilder() var fbb = FlatBufferBuilder()
let start = TestMutatingBool.startTestMutatingBool(&fbb) let start = TestMutatingBool.startTestMutatingBool(&fbb)
TestMutatingBool.add(b: createProperty(builder: &fbb), &fbb) TestMutatingBool.add(b: createProperty(builder: &fbb), &fbb)
let root = TestMutatingBool.endTestMutatingBool(&fbb, start: start) let root = TestMutatingBool.endTestMutatingBool(&fbb, start: start)
fbb.finish(offset: root) fbb.finish(offset: root)
let testMutatingBool = TestMutatingBool.getRootAsTestMutatingBool(bb: fbb.sizedBuffer) let testMutatingBool = TestMutatingBool.getRootAsTestMutatingBool(bb: fbb.sizedBuffer)
let property = testMutatingBool.b let property = testMutatingBool.b
XCTAssertEqual(property?.property, false) XCTAssertEqual(property?.property, false)
property?.mutate(property: false) property?.mutate(property: false)
XCTAssertEqual(property?.property, false) XCTAssertEqual(property?.property, false)
property?.mutate(property: true) property?.mutate(property: true)
XCTAssertEqual(property?.property, true) XCTAssertEqual(property?.property, true)
} }
} }
struct Vec: Readable { struct Vec: Readable {
var __buffer: ByteBuffer! { __p.bb } var __buffer: ByteBuffer! { __p.bb }
static var size = 12 static var size = 12
static var alignment = 4 static var alignment = 4
private var __p: Struct private var __p: Struct
init(_ fb: ByteBuffer, o: Int32) { __p = Struct(bb: fb, position: o) } init(_ fb: ByteBuffer, o: Int32) { __p = Struct(bb: fb, position: o) }
var x: Float32 { return __p.readBuffer(of: Float32.self, at: 0)} var x: Float32 { __p.readBuffer(of: Float32.self, at: 0)}
var y: Float32 { return __p.readBuffer(of: Float32.self, at: 4)} var y: Float32 { __p.readBuffer(of: Float32.self, at: 4)}
var z: Float32 { return __p.readBuffer(of: Float32.self, at: 8)} var z: Float32 { __p.readBuffer(of: Float32.self, at: 8)}
} }
@discardableResult @discardableResult
func createVecWrite(builder: inout FlatBufferBuilder, x: Float32, y: Float32, z: Float32) -> Offset<UOffset> { func createVecWrite(builder: inout FlatBufferBuilder, x: Float32, y: Float32, z: Float32) -> Offset<UOffset> {
builder.createStructOf(size: Vec.size, alignment: Vec.alignment) builder.createStructOf(size: Vec.size, alignment: Vec.alignment)
builder.reverseAdd(v: x, postion: 0) builder.reverseAdd(v: x, postion: 0)
builder.reverseAdd(v: y, postion: 4) builder.reverseAdd(v: y, postion: 4)
builder.reverseAdd(v: z, postion: 8) builder.reverseAdd(v: z, postion: 8)
return builder.endStruct() return builder.endStruct()
} }

View File

@@ -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 import XCTest
@testable import FlatBuffers @testable import FlatBuffers
final class FlatBuffersTests: XCTestCase { final class FlatBuffersTests: XCTestCase {
let country = "Norway" let country = "Norway"
func testEndian() { XCTAssertEqual(isLitteEndian, true) } func testEndian() { XCTAssertEqual(isLitteEndian, true) }
func testOffset() { func testOffset() {
let o = Offset<Int>() let o = Offset<Int>()
let b = Offset<Int>(offset: 1) let b = Offset<Int>(offset: 1)
XCTAssertEqual(o.isEmpty, true) XCTAssertEqual(o.isEmpty, true)
XCTAssertEqual(b.isEmpty, false) XCTAssertEqual(b.isEmpty, false)
} }
func testCreateString() { func testCreateString() {
let helloWorld = "Hello, world!" let helloWorld = "Hello, world!"
var b = FlatBufferBuilder(initialSize: 16) var b = FlatBufferBuilder(initialSize: 16)
XCTAssertEqual(b.create(string: country).o, 12) XCTAssertEqual(b.create(string: country).o, 12)
XCTAssertEqual(b.create(string: helloWorld).o, 32) XCTAssertEqual(b.create(string: helloWorld).o, 32)
b.clear() b.clear()
XCTAssertEqual(b.create(string: helloWorld).o, 20) XCTAssertEqual(b.create(string: helloWorld).o, 20)
XCTAssertEqual(b.create(string: country).o, 32) XCTAssertEqual(b.create(string: country).o, 32)
b.clear() b.clear()
XCTAssertEqual(b.create(string: String(repeating: "a", count: 257)).o, 264) XCTAssertEqual(b.create(string: String(repeating: "a", count: 257)).o, 264)
} }
func testStartTable() { func testStartTable() {
var b = FlatBufferBuilder(initialSize: 16) var b = FlatBufferBuilder(initialSize: 16)
XCTAssertNoThrow(b.startTable(with: 0)) XCTAssertNoThrow(b.startTable(with: 0))
b.clear() b.clear()
XCTAssertEqual(b.create(string: country).o, 12) XCTAssertEqual(b.create(string: country).o, 12)
XCTAssertEqual(b.startTable(with: 0), 12) XCTAssertEqual(b.startTable(with: 0), 12)
} }
func testCreateFinish() { func testCreateFinish() {
var b = FlatBufferBuilder(initialSize: 16) var b = FlatBufferBuilder(initialSize: 16)
let countryOff = Country.createCountry(builder: &b, name: country, log: 200, lan: 100) let countryOff = Country.createCountry(builder: &b, name: country, log: 200, lan: 100)
b.finish(offset: countryOff) 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] 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) XCTAssertEqual(b.sizedByteArray, v)
} }
func testCreateFinishWithPrefix() { func testCreateFinishWithPrefix() {
var b = FlatBufferBuilder(initialSize: 16) var b = FlatBufferBuilder(initialSize: 16)
let countryOff = Country.createCountry(builder: &b, name: country, log: 200, lan: 100) let countryOff = Country.createCountry(builder: &b, name: country, log: 200, lan: 100)
b.finish(offset: countryOff, addPrefix: true) 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] 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) XCTAssertEqual(b.sizedByteArray, v)
} }
func testReadCountry() { 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 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 buffer = ByteBuffer(bytes: v)
let c = Country.getRootAsCountry(buffer) let c = Country.getRootAsCountry(buffer)
XCTAssertEqual(c.lan, 100) XCTAssertEqual(c.lan, 100)
XCTAssertEqual(c.log, 200) XCTAssertEqual(c.log, 200)
XCTAssertEqual(c.nameVector, [78, 111, 114, 119, 97, 121]) XCTAssertEqual(c.nameVector, [78, 111, 114, 119, 97, 121])
XCTAssertEqual(c.name, country) XCTAssertEqual(c.name, country)
} }
func testWriteNullableStrings() { func testWriteNullableStrings() {
var b = FlatBufferBuilder() var b = FlatBufferBuilder()
XCTAssertTrue(b.create(string: nil).isEmpty) XCTAssertTrue(b.create(string: nil).isEmpty)
XCTAssertTrue(b.createShared(string: nil).isEmpty) XCTAssertTrue(b.createShared(string: nil).isEmpty)
} }
func testWriteOptionalValues() { func testWriteOptionalValues() {
var b = FlatBufferBuilder() var b = FlatBufferBuilder()
let root = optional_scalars_ScalarStuff.createScalarStuff(&b, let root = optional_scalars_ScalarStuff.createScalarStuff(
justI8: 80, &b,
maybeI8: nil, justI8: 80,
justU8: 100, maybeI8: nil,
maybeU8: 10, justU8: 100,
maybeBool: true, maybeU8: 10,
justEnum: .one, maybeBool: true,
maybeEnum: nil) justEnum: .one,
b.finish(offset: root) maybeEnum: nil)
let scalarTable = optional_scalars_ScalarStuff.getRootAsScalarStuff(bb: b.sizedBuffer) b.finish(offset: root)
XCTAssertEqual(scalarTable.justI8, 80) let scalarTable = optional_scalars_ScalarStuff.getRootAsScalarStuff(bb: b.sizedBuffer)
XCTAssertNil(scalarTable.maybeI8) XCTAssertEqual(scalarTable.justI8, 80)
XCTAssertEqual(scalarTable.maybeBool, true) XCTAssertNil(scalarTable.maybeI8)
XCTAssertEqual(scalarTable.defaultI8, 42) XCTAssertEqual(scalarTable.maybeBool, true)
XCTAssertEqual(scalarTable.justU8, 100) XCTAssertEqual(scalarTable.defaultI8, 42)
XCTAssertEqual(scalarTable.maybeU8, 10) XCTAssertEqual(scalarTable.justU8, 100)
XCTAssertEqual(scalarTable.justEnum, .one) XCTAssertEqual(scalarTable.maybeU8, 10)
XCTAssertNil(scalarTable.maybeEnum) XCTAssertEqual(scalarTable.justEnum, .one)
} XCTAssertNil(scalarTable.maybeEnum)
}
} }
class Country { class Country {
static let offsets: (name: VOffset, lan: VOffset, lng: VOffset) = (4, 6, 8) static let offsets: (name: VOffset, lan: VOffset, lng: VOffset) = (4, 6, 8)
private var __t: Table private var __t: Table
private init(_ t: Table) { private init(_ t: Table) {
__t = t __t = t
} }
var lan: Int32 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(of: Int32.self, at: o) } 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 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 nameVector: [UInt8]? { __t.getVector(at: 4) }
var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) } var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) }
@inlinable static func getRootAsCountry(_ bb: ByteBuffer) -> Country { @inlinable
return Country(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0)))) 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<Country> { @inlinable
return createCountry(builder: &builder, offset: builder.create(string: name), log: log, lan: lan) static func createCountry(
} builder: inout FlatBufferBuilder,
name: String,
log: Int32,
lan: Int32) -> Offset<Country>
{
createCountry(builder: &builder, offset: builder.create(string: name), log: log, lan: lan)
}
@inlinable static func createCountry(builder: inout FlatBufferBuilder, offset: Offset<String>, log: Int32, lan: Int32) -> Offset<Country> { @inlinable
let _start = builder.startTable(with: 3) static func createCountry(
Country.add(builder: &builder, lng: log) builder: inout FlatBufferBuilder,
Country.add(builder: &builder, lan: lan) offset: Offset<String>,
Country.add(builder: &builder, name: offset) log: Int32,
return Country.end(builder: &builder, startOffset: _start) lan: Int32) -> Offset<Country>
} {
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<Country> { @inlinable
return Offset(offset: builder.endTable(at: startOffset)) static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Country> {
} Offset(offset: builder.endTable(at: startOffset))
}
@inlinable static func add(builder: inout FlatBufferBuilder, name: String) { @inlinable
add(builder: &builder, name: builder.create(string: name)) 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<String>) { @inlinable
builder.add(offset: name, at: Country.offsets.name) static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
} builder.add(offset: name, at: Country.offsets.name)
}
@inlinable static func add(builder: inout FlatBufferBuilder, lan: Int32) { @inlinable
builder.add(element: lan, def: 0, at: Country.offsets.lan) 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) { @inlinable
builder.add(element: lng, def: 0, at: Country.offsets.lng) static func add(builder: inout FlatBufferBuilder, lng: Int32) {
} builder.add(element: lng, def: 0, at: Country.offsets.lng)
}
} }

View File

@@ -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 import XCTest
@testable import FlatBuffers @testable import FlatBuffers
final class FlatBuffersUnionTests: XCTestCase { final class FlatBuffersUnionTests: XCTestCase {
func testCreateMonstor() { func testCreateMonstor() {
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let dmg: Int16 = 5 let dmg: Int16 = 5
let str = "Axe" let str = "Axe"
let axe = b.create(string: str) let axe = b.create(string: str)
let weapon = Weapon.createWeapon(builder: &b, offset: axe, dmg: dmg) let weapon = Weapon.createWeapon(builder: &b, offset: axe, dmg: dmg)
let weapons = b.createVector(ofOffsets: [weapon]) let weapons = b.createVector(ofOffsets: [weapon])
let root = LocalMonster.createMonster(builder: &b, let root = LocalMonster.createMonster(
offset: weapons, builder: &b,
equipment: .Weapon, offset: weapons,
equippedOffset: weapon.o) equipment: .Weapon,
b.finish(offset: root) equippedOffset: weapon.o)
let buffer = b.sizedByteArray b.finish(offset: root)
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 buffer = b.sizedByteArray
let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer)) 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])
XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg) let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer))
XCTAssertEqual(monster.weapon(at: 0)?.name, str) XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg)
XCTAssertEqual(monster.weapon(at: 0)?.nameVector, [65, 120, 101]) XCTAssertEqual(monster.weapon(at: 0)?.name, str)
let p: Weapon? = monster.equiped() XCTAssertEqual(monster.weapon(at: 0)?.nameVector, [65, 120, 101])
XCTAssertEqual(p?.dmg, dmg) let p: Weapon? = monster.equiped()
XCTAssertEqual(p?.name, str) XCTAssertEqual(p?.dmg, dmg)
XCTAssertEqual(p?.nameVector, [65, 120, 101]) 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..<movie.charactersTypeCount {
XCTAssertEqual(movie.charactersType(at: i), characterType[Int(i)])
} }
func testEndTableFinish() { XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, 7)
var builder = FlatBufferBuilder(initialSize: 20) XCTAssertEqual(movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, swordDmg)
let sword = builder.create(string: "Sword") XCTAssertEqual(movie.characters(at: 2, type: BookReader.self)?.booksRead, 2)
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() { var objc: MovieT? = movie.unpack()
let vectorOfEnums: [ColorsNameSpace.RGB] = [.blue, .green] XCTAssertEqual(movie.charactersTypeCount, Int32(objc?.characters.count ?? 0))
XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, (objc?.characters[0]?.value as? BookReaderT)?.booksRead)
fb.clear()
let newMovie = Movie.pack(&fb, obj: &objc)
fb.finish(offset: newMovie)
var builder = FlatBufferBuilder(initialSize: 1) let packedMovie = Movie.getRootAsMovie(bb: fb.buffer)
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() { XCTAssertEqual(packedMovie.characters(at: 0, type: BookReader.self)?.booksRead, movie.characters(at: 0, type: BookReader.self)?.booksRead)
var fb = FlatBufferBuilder() XCTAssertEqual(packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage)
XCTAssertEqual(packedMovie.characters(at: 2, type: BookReader.self)?.booksRead, movie.characters(at: 2, type: BookReader.self)?.booksRead)
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..<movie.charactersTypeCount {
XCTAssertEqual(movie.charactersType(at: i), characterType[Int(i)])
}
XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, 7)
XCTAssertEqual(movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, swordDmg)
XCTAssertEqual(movie.characters(at: 2, type: BookReader.self)?.booksRead, 2)
var objc: MovieT? = movie.unpack()
XCTAssertEqual(movie.charactersTypeCount, Int32(objc?.characters.count ?? 0))
XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, (objc?.characters[0]?.value as? BookReaderT)?.booksRead)
fb.clear()
let newMovie = Movie.pack(&fb, obj: &objc)
fb.finish(offset: newMovie)
let packedMovie = Movie.getRootAsMovie(bb: fb.buffer)
XCTAssertEqual(packedMovie.characters(at: 0, type: BookReader.self)?.booksRead, movie.characters(at: 0, type: BookReader.self)?.booksRead)
XCTAssertEqual(packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage)
XCTAssertEqual(packedMovie.characters(at: 2, type: BookReader.self)?.booksRead, movie.characters(at: 2, type: BookReader.self)?.booksRead)
}
} }
public enum ColorsNameSpace { public enum ColorsNameSpace {
enum RGB: Int32, Enum { enum RGB: Int32, Enum {
typealias T = Int32 typealias T = Int32
static var byteSize: Int { return MemoryLayout<Int32>.size } static var byteSize: Int { MemoryLayout<Int32>.size }
var value: Int32 { return self.rawValue } var value: Int32 { rawValue }
case red = 0, green = 1, blue = 2 case red = 0, green = 1, blue = 2
} }
struct Monster: FlatBufferObject { struct Monster: FlatBufferObject {
var __buffer: ByteBuffer! { _accessor.bb } var __buffer: ByteBuffer! { _accessor.bb }
private var _accessor: Table 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))) } 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(_ t: Table) { _accessor = t }
init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } 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 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)) } 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(
static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } of: Int32.self,
static func add(colors: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: colors, at: 4) } offset: _accessor.vector(at: o) + index * 4)) }
static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
} static func add(colors: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(
offset: colors,
at: 4) }
static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
}
} }
@@ -152,91 +176,107 @@ enum Color3: Int8 { case red = 0, green, blue }
struct FinalMonster { struct FinalMonster {
@inlinable static func createMonster(builder: inout FlatBufferBuilder, @inlinable
position: Offset<UOffset>, static func createMonster(
hp: Int16, builder: inout FlatBufferBuilder,
name: Offset<String>, position: Offset<UOffset>,
inventory: Offset<UOffset>, hp: Int16,
color: Color3, name: Offset<String>,
weapons: Offset<UOffset>, inventory: Offset<UOffset>,
equipment: Equipment = .none, color: Color3,
equippedOffset: Offset<Weapon>, weapons: Offset<UOffset>,
path: Offset<UOffset>) -> Offset<LocalMonster> { equipment: Equipment = .none,
let start = builder.startTable(with: 11) equippedOffset: Offset<Weapon>,
builder.add(structOffset: 4) path: Offset<UOffset>) -> Offset<LocalMonster>
builder.add(element: hp, def: 100, at: 8) {
builder.add(offset: name, at: 10) let start = builder.startTable(with: 11)
builder.add(offset: inventory, at: 14) builder.add(structOffset: 4)
builder.add(element: color.rawValue, def: Color3.green.rawValue, at: 16) builder.add(element: hp, def: 100, at: 8)
builder.add(offset: weapons, at: 18) builder.add(offset: name, at: 10)
builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 20) builder.add(offset: inventory, at: 14)
builder.add(offset: equippedOffset, at: 22) builder.add(element: color.rawValue, def: Color3.green.rawValue, at: 16)
builder.add(offset: path, at: 24) builder.add(offset: weapons, at: 18)
return Offset(offset: builder.endTable(at: start)) 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 { struct LocalMonster {
private var __t: Table private var __t: Table
init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o) } init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o) }
init(_ t: Table) { __t = t } 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 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: FlatBufferObject>() -> T? { func equiped<T: FlatBufferObject>() -> T? {
let o = __t.offset(8); return o == 0 ? nil : __t.union(o) let o = __t.offset(8); return o == 0 ? nil : __t.union(o)
} }
static func getRootAsMonster(bb: ByteBuffer) -> LocalMonster { static func getRootAsMonster(bb: ByteBuffer) -> LocalMonster {
return LocalMonster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0)))) LocalMonster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
} }
@inlinable static func createMonster(builder: inout FlatBufferBuilder, @inlinable
offset: Offset<UOffset>, static func createMonster(
equipment: Equipment = .none, builder: inout FlatBufferBuilder,
equippedOffset: UOffset) -> Offset<LocalMonster> { offset: Offset<UOffset>,
let start = builder.startTable(with: 3) equipment: Equipment = .none,
builder.add(element: equippedOffset, def: 0, at: 8) equippedOffset: UOffset) -> Offset<LocalMonster>
builder.add(offset: offset, at: 4) {
builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 6) let start = builder.startTable(with: 3)
return Offset(offset: builder.endTable(at: start)) 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 { struct Weapon: FlatBufferObject {
var __buffer: ByteBuffer! { __t.bb } var __buffer: ByteBuffer! { __t.bb }
static let offsets: (name: VOffset, dmg: VOffset) = (4, 6) static let offsets: (name: VOffset, dmg: VOffset) = (4, 6)
private var __t: Table private var __t: Table
init(_ t: Table) { __t = t } init(_ t: Table) { __t = t }
init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o)} 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 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 nameVector: [UInt8]? { __t.getVector(at: 4) }
var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) } 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)) } static func assign(_ i: Int32, _ bb: ByteBuffer) -> Weapon { Weapon(Table(bb: bb, position: i)) }
@inlinable static func createWeapon(builder: inout FlatBufferBuilder, offset: Offset<String>, dmg: Int16) -> Offset<Weapon> { @inlinable
let _start = builder.startTable(with: 2) static func createWeapon(
Weapon.add(builder: &builder, name: offset) builder: inout FlatBufferBuilder,
Weapon.add(builder: &builder, dmg: dmg) offset: Offset<String>,
return Weapon.end(builder: &builder, startOffset: _start) dmg: Int16) -> Offset<Weapon>
} {
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<Weapon> { @inlinable
return Offset(offset: builder.endTable(at: startOffset)) static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Weapon> {
} Offset(offset: builder.endTable(at: startOffset))
}
@inlinable static func add(builder: inout FlatBufferBuilder, name: Offset<String>) { @inlinable
builder.add(offset: name, at: Weapon.offsets.name) static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
} builder.add(offset: name, at: Weapon.offsets.name)
}
@inlinable static func add(builder: inout FlatBufferBuilder, dmg: Int16) { @inlinable
builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg) static func add(builder: inout FlatBufferBuilder, dmg: Int16) {
} builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg)
}
} }

View File

@@ -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 import XCTest
@testable import FlatBuffers @testable import FlatBuffers
final class FlatBuffersVectors: XCTestCase { final class FlatBuffersVectors: XCTestCase {
func testCreatingTwoCountries() { func testCreatingTwoCountries() {
let norway = "Norway" let norway = "Norway"
let denmark = "Denmark" let denmark = "Denmark"
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let noStr = b.create(string: norway) let noStr = b.create(string: norway)
let deStr = b.create(string: denmark) let deStr = b.create(string: denmark)
let n = Country.createCountry(builder: &b, offset: noStr, log: 888, lan: 700) 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 d = Country.createCountry(builder: &b, offset: deStr, log: 200, lan: 100)
let vector = [n, d] let vector = [n, d]
let vectorOffset = b.createVector(ofOffsets: vector) let vectorOffset = b.createVector(ofOffsets: vector)
b.finish(offset: vectorOffset) 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]) 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() { func testCreateIntArray() {
let numbers: [Int32] = [1, 2, 3, 4, 5] let numbers: [Int32] = [1, 2, 3, 4, 5]
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let o = b.createVector(numbers, size: numbers.count) let o = b.createVector(numbers, size: numbers.count)
b.finish(offset: o) 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]) 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() { func testCreateEmptyIntArray() {
let numbers: [Int32] = [] let numbers: [Int32] = []
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let o = b.createVector(numbers, size: numbers.count) let o = b.createVector(numbers, size: numbers.count)
b.finish(offset: o) b.finish(offset: o)
XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 0, 0, 0, 0]) XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 0, 0, 0, 0])
} }
func testCreateVectorOfStrings() { func testCreateVectorOfStrings() {
let strs = ["Denmark", "Norway"] let strs = ["Denmark", "Norway"]
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let o = b.createVector(ofStrings: strs) let o = b.createVector(ofStrings: strs)
b.finish(offset: o) 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]) 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() { func testCreateSharedStringVector() {
let norway = "Norway" let norway = "Norway"
let denmark = "Denmark" let denmark = "Denmark"
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let noStr = b.createShared(string: norway) let noStr = b.createShared(string: norway)
let deStr = b.createShared(string: denmark) let deStr = b.createShared(string: denmark)
let _noStr = b.createShared(string: norway) let _noStr = b.createShared(string: norway)
let _deStr = b.createShared(string: denmark) let _deStr = b.createShared(string: denmark)
let v = [noStr, deStr, _noStr, _deStr] let v = [noStr, deStr, _noStr, _deStr]
let end = b.createVector(ofOffsets: v) let end = b.createVector(ofOffsets: v)
b.finish(offset: end) 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]) 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() { func testReadInt32Array() {
let data: [Int32] = [1, 2, 3, 4, 5] let data: [Int32] = [1, 2, 3, 4, 5]
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let v = Numbers.createNumbersVector(b: &b, array: data) let v = Numbers.createNumbersVector(b: &b, array: data)
let end = Numbers.createNumbers(b: &b, o: v) let end = Numbers.createNumbers(b: &b, o: v)
b.finish(offset: end) b.finish(offset: end)
let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray)) let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray))
XCTAssertEqual(number.vArrayInt32, [1, 2, 3, 4, 5]) XCTAssertEqual(number.vArrayInt32, [1, 2, 3, 4, 5])
} }
func testReadDoubleArray() { func testReadDoubleArray() {
let data: [Double] = [1, 2, 3, 4, 5] let data: [Double] = [1, 2, 3, 4, 5]
var b = FlatBufferBuilder(initialSize: 20) var b = FlatBufferBuilder(initialSize: 20)
let v = Numbers.createNumbersVector(b: &b, array: data) let v = Numbers.createNumbersVector(b: &b, array: data)
let end = Numbers.createNumbers(b: &b, o: v) let end = Numbers.createNumbers(b: &b, o: v)
b.finish(offset: end) b.finish(offset: end)
let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray)) let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray))
XCTAssertEqual(number.vArrayDouble, [1, 2, 3, 4, 5]) XCTAssertEqual(number.vArrayDouble, [1, 2, 3, 4, 5])
} }
} }
struct Numbers { struct Numbers {
private var __t: Table private var __t: Table
private init(_ t: Table) { private init(_ t: Table) {
__t = t __t = t
} }
@inlinable static func getRootAsNumbers(_ bb: ByteBuffer) -> Numbers { @inlinable
return Numbers(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0)))) static func getRootAsNumbers(_ bb: ByteBuffer) -> Numbers {
} Numbers(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
}
var vArrayInt: [Int]? { return __t.getVector(at: 4) } var vArrayInt: [Int]? { __t.getVector(at: 4) }
var vArrayInt32: [Int32]? { return __t.getVector(at: 4) } var vArrayInt32: [Int32]? { __t.getVector(at: 4) }
var vArrayDouble: [Double]? { return __t.getVector(at: 4) } var vArrayDouble: [Double]? { __t.getVector(at: 4) }
var vArrayFloat: [Float32]? { return __t.getVector(at: 4) } var vArrayFloat: [Float32]? { __t.getVector(at: 4) }
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int]) -> Offset<UOffset> { static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int]) -> Offset<UOffset> {
return b.createVector(array, size: array.count) b.createVector(array, size: array.count)
} }
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int32]) -> Offset<UOffset> { static func createNumbersVector(b: inout FlatBufferBuilder, array: [Int32]) -> Offset<UOffset> {
return b.createVector(array, size: array.count) b.createVector(array, size: array.count)
} }
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Double]) -> Offset<UOffset> { static func createNumbersVector(b: inout FlatBufferBuilder, array: [Double]) -> Offset<UOffset> {
return b.createVector(array, size: array.count) b.createVector(array, size: array.count)
} }
static func createNumbersVector(b: inout FlatBufferBuilder, array: [Float32]) -> Offset<UOffset> { static func createNumbersVector(b: inout FlatBufferBuilder, array: [Float32]) -> Offset<UOffset> {
return b.createVector(array, size: array.count) b.createVector(array, size: array.count)
} }
static func createNumbers(b: inout FlatBufferBuilder, o: Offset<UOffset>) -> Offset<UOffset> { static func createNumbers(b: inout FlatBufferBuilder, o: Offset<UOffset>) -> Offset<UOffset> {
let start = b.startTable(with: 1) let start = b.startTable(with: 1)
b.add(offset: o, at: 4) b.add(offset: o, at: 4)
return Offset(offset: b.endTable(at: start)) return Offset(offset: b.endTable(at: start))
} }
} }

View File

@@ -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 import XCTest
@testable import FlatBuffers @testable import FlatBuffers
final class FlatBuffersDoubleTests: XCTestCase { final class FlatBuffersDoubleTests: XCTestCase {
let country = "Norway" let country = "Norway"
func testCreateFinish() { func testCreateFinish() {
var b = FlatBufferBuilder(initialSize: 16) var b = FlatBufferBuilder(initialSize: 16)
let countryOff = CountryDouble.createCountry(builder: &b, name: country, log: 200, lan: 100) let countryOff = CountryDouble.createCountry(builder: &b, name: country, log: 200, lan: 100)
b.finish(offset: countryOff) 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] 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) XCTAssertEqual(b.sizedByteArray, v)
} }
func testCreateFinishWithPrefix() { func testCreateFinishWithPrefix() {
var b = FlatBufferBuilder(initialSize: 16) var b = FlatBufferBuilder(initialSize: 16)
let countryOff = CountryDouble.createCountry(builder: &b, name: country, log: 200, lan: 100) let countryOff = CountryDouble.createCountry(builder: &b, name: country, log: 200, lan: 100)
b.finish(offset: countryOff, addPrefix: true) 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] 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) XCTAssertEqual(b.sizedByteArray, v)
} }
} }
class CountryDouble { class CountryDouble {
static let offsets: (name: VOffset, lan: VOffset, lng: VOffset) = (4, 6, 8) static let offsets: (name: VOffset, lan: VOffset, lng: VOffset) = (4, 6, 8)
private var table: Table private var table: Table
private init(table t: Table) { table = t } private init(table t: Table) { table = t }
static func getRootAsCountry(_ bb: ByteBuffer) -> CountryDouble { static func getRootAsCountry(_ bb: ByteBuffer) -> CountryDouble {
let pos = bb.read(def: Int32.self, position: Int(bb.size)) let pos = bb.read(def: Int32.self, position: Int(bb.size))
return CountryDouble(table: Table(bb: bb, position: Int32(pos))) return CountryDouble(table: Table(bb: bb, position: Int32(pos)))
} }
static func createCountry(builder: inout FlatBufferBuilder, name: String, log: Double, lan: Double) -> Offset<Country> { static func createCountry(
return createCountry(builder: &builder, offset: builder.create(string: name), log: log, lan: lan) builder: inout FlatBufferBuilder,
} name: String,
log: Double,
lan: Double) -> Offset<Country>
{
createCountry(builder: &builder, offset: builder.create(string: name), log: log, lan: lan)
}
static func createCountry(builder: inout FlatBufferBuilder, offset: Offset<String>, log: Double, lan: Double) -> Offset<Country> { static func createCountry(
let _start = builder.startTable(with: 3) builder: inout FlatBufferBuilder,
CountryDouble.add(builder: &builder, lng: log) offset: Offset<String>,
CountryDouble.add(builder: &builder, lan: lan) log: Double,
CountryDouble.add(builder: &builder, name: offset) lan: Double) -> Offset<Country>
return CountryDouble.end(builder: &builder, startOffset: _start) {
} 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<Country> { static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Country> {
return Offset(offset: builder.endTable(at: startOffset)) Offset(offset: builder.endTable(at: startOffset))
} }
static func add(builder: inout FlatBufferBuilder, name: String) { static func add(builder: inout FlatBufferBuilder, name: String) {
add(builder: &builder, name: builder.create(string: name)) add(builder: &builder, name: builder.create(string: name))
} }
static func add(builder: inout FlatBufferBuilder, name: Offset<String>) { static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
builder.add(offset: name, at: Country.offsets.name) builder.add(offset: name, at: Country.offsets.name)
} }
static func add(builder: inout FlatBufferBuilder, lan: Double) { static func add(builder: inout FlatBufferBuilder, lan: Double) {
builder.add(element: lan, def: 0, at: Country.offsets.lan) builder.add(element: lan, def: 0, at: Country.offsets.lan)
} }
static func add(builder: inout FlatBufferBuilder, lng: Double) { static func add(builder: inout FlatBufferBuilder, lng: Double) {
builder.add(element: lng, def: 0, at: Country.offsets.lng) builder.add(element: lng, def: 0, at: Country.offsets.lng)
} }
} }

View File

@@ -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) #if !canImport(ObjectiveC)
import XCTest import XCTest
extension FlatBuffersDoubleTests { extension FlatBuffersDoubleTests {
// DO NOT MODIFY: This is autogenerated, use: // DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain` // `swift test --generate-linuxmain`
// to regenerate. // to regenerate.
static let __allTests__FlatBuffersDoubleTests = [ static let __allTests__FlatBuffersDoubleTests = [
("testCreateFinish", testCreateFinish), ("testCreateFinish", testCreateFinish),
("testCreateFinishWithPrefix", testCreateFinishWithPrefix), ("testCreateFinishWithPrefix", testCreateFinishWithPrefix),
] ]
} }
extension FlatBuffersMonsterWriterTests { extension FlatBuffersMonsterWriterTests {
// DO NOT MODIFY: This is autogenerated, use: // DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain` // `swift test --generate-linuxmain`
// to regenerate. // to regenerate.
static let __allTests__FlatBuffersMonsterWriterTests = [ static let __allTests__FlatBuffersMonsterWriterTests = [
("testCreateMonster", testCreateMonster), ("testCreateMonster", testCreateMonster),
("testCreateMonsterPrefixed", testCreateMonsterPrefixed), ("testCreateMonsterPrefixed", testCreateMonsterPrefixed),
("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer), ("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer),
("testCreateMonsterUsingCreateMonsterMethodWithNilPos", testCreateMonsterUsingCreateMonsterMethodWithNilPos), (
("testCreateMonsterUsingCreateMonsterMethodWithPosX", testCreateMonsterUsingCreateMonsterMethodWithPosX), "testCreateMonsterUsingCreateMonsterMethodWithNilPos",
("testData", testData), testCreateMonsterUsingCreateMonsterMethodWithNilPos),
("testReadFromOtherLanguages", testReadFromOtherLanguages), (
("testReadMonsterFromUnsafePointerWithoutCopying", testReadMonsterFromUnsafePointerWithoutCopying), "testCreateMonsterUsingCreateMonsterMethodWithPosX",
] testCreateMonsterUsingCreateMonsterMethodWithPosX),
("testData", testData),
("testReadFromOtherLanguages", testReadFromOtherLanguages),
(
"testReadMonsterFromUnsafePointerWithoutCopying",
testReadMonsterFromUnsafePointerWithoutCopying),
]
} }
extension FlatBuffersStructsTests { extension FlatBuffersStructsTests {
// DO NOT MODIFY: This is autogenerated, use: // DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain` // `swift test --generate-linuxmain`
// to regenerate. // to regenerate.
static let __allTests__FlatBuffersStructsTests = [ static let __allTests__FlatBuffersStructsTests = [
("testWritingAndMutatingBools", testWritingAndMutatingBools), ("testWritingAndMutatingBools", testWritingAndMutatingBools),
] ]
} }
extension FlatBuffersTests { extension FlatBuffersTests {
// DO NOT MODIFY: This is autogenerated, use: // DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain` // `swift test --generate-linuxmain`
// to regenerate. // to regenerate.
static let __allTests__FlatBuffersTests = [ static let __allTests__FlatBuffersTests = [
("testCreateFinish", testCreateFinish), ("testCreateFinish", testCreateFinish),
("testCreateFinishWithPrefix", testCreateFinishWithPrefix), ("testCreateFinishWithPrefix", testCreateFinishWithPrefix),
("testCreateString", testCreateString), ("testCreateString", testCreateString),
("testEndian", testEndian), ("testEndian", testEndian),
("testOffset", testOffset), ("testOffset", testOffset),
("testReadCountry", testReadCountry), ("testReadCountry", testReadCountry),
("testStartTable", testStartTable), ("testStartTable", testStartTable),
("testWriteNullableStrings", testWriteNullableStrings), ("testWriteNullableStrings", testWriteNullableStrings),
("testWriteOptionalValues", testWriteOptionalValues), ("testWriteOptionalValues", testWriteOptionalValues),
] ]
} }
extension FlatBuffersUnionTests { extension FlatBuffersUnionTests {
// DO NOT MODIFY: This is autogenerated, use: // DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain` // `swift test --generate-linuxmain`
// to regenerate. // to regenerate.
static let __allTests__FlatBuffersUnionTests = [ static let __allTests__FlatBuffersUnionTests = [
("testCreateMonstor", testCreateMonstor), ("testCreateMonstor", testCreateMonstor),
("testEndTableFinish", testEndTableFinish), ("testEndTableFinish", testEndTableFinish),
("testEnumVector", testEnumVector), ("testEnumVector", testEnumVector),
("testUnionVector", testUnionVector), ("testUnionVector", testUnionVector),
] ]
} }
extension FlatBuffersVectors { extension FlatBuffersVectors {
// DO NOT MODIFY: This is autogenerated, use: // DO NOT MODIFY: This is autogenerated, use:
// `swift test --generate-linuxmain` // `swift test --generate-linuxmain`
// to regenerate. // to regenerate.
static let __allTests__FlatBuffersVectors = [ static let __allTests__FlatBuffersVectors = [
("testCreateEmptyIntArray", testCreateEmptyIntArray), ("testCreateEmptyIntArray", testCreateEmptyIntArray),
("testCreateIntArray", testCreateIntArray), ("testCreateIntArray", testCreateIntArray),
("testCreateSharedStringVector", testCreateSharedStringVector), ("testCreateSharedStringVector", testCreateSharedStringVector),
("testCreateVectorOfStrings", testCreateVectorOfStrings), ("testCreateVectorOfStrings", testCreateVectorOfStrings),
("testCreatingTwoCountries", testCreatingTwoCountries), ("testCreatingTwoCountries", testCreatingTwoCountries),
("testReadDoubleArray", testReadDoubleArray), ("testReadDoubleArray", testReadDoubleArray),
("testReadInt32Array", testReadInt32Array), ("testReadInt32Array", testReadInt32Array),
] ]
} }
public func __allTests() -> [XCTestCaseEntry] { public func __allTests() -> [XCTestCaseEntry] {
return [ [
testCase(FlatBuffersDoubleTests.__allTests__FlatBuffersDoubleTests), testCase(FlatBuffersDoubleTests.__allTests__FlatBuffersDoubleTests),
testCase(FlatBuffersMonsterWriterTests.__allTests__FlatBuffersMonsterWriterTests), testCase(FlatBuffersMonsterWriterTests.__allTests__FlatBuffersMonsterWriterTests),
testCase(FlatBuffersStructsTests.__allTests__FlatBuffersStructsTests), testCase(FlatBuffersStructsTests.__allTests__FlatBuffersStructsTests),
testCase(FlatBuffersTests.__allTests__FlatBuffersTests), testCase(FlatBuffersTests.__allTests__FlatBuffersTests),
testCase(FlatBuffersUnionTests.__allTests__FlatBuffersUnionTests), testCase(FlatBuffersUnionTests.__allTests__FlatBuffersUnionTests),
testCase(FlatBuffersVectors.__allTests__FlatBuffersVectors), testCase(FlatBuffersVectors.__allTests__FlatBuffersVectors),
] ]
} }
#endif #endif

View File

@@ -1,6 +1,10 @@
// Generated GRPC code for FlatBuffers swift! // Generated GRPC code for FlatBuffers swift!
/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-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 /// in case of an issue please open github issue, though it would be maintained
// swiftlint:disable all
// swiftformat:disable all
import Foundation import Foundation
import GRPC import GRPC
import NIO import NIO
@@ -9,87 +13,85 @@ import FlatBuffers
public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {} public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {}
public extension GRPCFlatBufPayload { public extension GRPCFlatBufPayload {
init(serializedByteBuffer: inout NIO.ByteBuffer) throws { init(serializedByteBuffer: inout NIO.ByteBuffer) throws {
self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes))
} }
func serialize(into buffer: inout NIO.ByteBuffer) throws { func serialize(into buffer: inout NIO.ByteBuffer) throws {
let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size)) let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size))
buffer.writeBytes(buf) buffer.writeBytes(buf)
} }
} }
extension Message: GRPCFlatBufPayload {} extension Message: GRPCFlatBufPayload {}
/// Usage: instantiate MyGame_Example_MonsterStorageServiceClient, then call methods of this protocol to make API calls. /// Usage: instantiate MyGame_Example_MonsterStorageServiceClient, then call methods of this protocol to make API calls.
public protocol MyGame_Example_MonsterStorageService { public protocol MyGame_Example_MonsterStorageService {
func Store(_ request: Message<MyGame_Example_Monster>, callOptions: CallOptions?) -> UnaryCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> func Store(_ request: Message<MyGame_Example_Monster>, callOptions: CallOptions?) -> UnaryCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>>
func Retrieve(_ request: Message<MyGame_Example_Stat>, callOptions: CallOptions?, handler: @escaping (Message<MyGame_Example_Monster>) -> Void) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>> func Retrieve(_ request: Message<MyGame_Example_Stat>, callOptions: CallOptions?, handler: @escaping (Message<MyGame_Example_Monster>) -> Void) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>>
func GetMaxHitPoint(callOptions: CallOptions?) -> ClientStreamingCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> func GetMaxHitPoint(callOptions: CallOptions?) -> ClientStreamingCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>>
func GetMinMaxHitPoints(callOptions: CallOptions?, handler: @escaping (Message<MyGame_Example_Stat>) -> Void) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> func GetMinMaxHitPoints(callOptions: CallOptions?, handler: @escaping (Message<MyGame_Example_Stat>) -> Void) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>>
} }
public final class MyGame_Example_MonsterStorageServiceClient: GRPCClient, MyGame_Example_MonsterStorageService { public final class MyGame_Example_MonsterStorageServiceClient: GRPCClient, MyGame_Example_MonsterStorageService {
public let channel: GRPCChannel public let channel: GRPCChannel
public var defaultCallOptions: CallOptions public var defaultCallOptions: CallOptions
public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) { public init(channel: GRPCChannel, defaultCallOptions: CallOptions = CallOptions()) {
self.channel = channel self.channel = channel
self.defaultCallOptions = defaultCallOptions self.defaultCallOptions = defaultCallOptions
} }
public func Store(_ request: Message<MyGame_Example_Monster>, callOptions: CallOptions? = nil) -> UnaryCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> { public func Store(_ request: Message<MyGame_Example_Monster>, callOptions: CallOptions? = nil) -> UnaryCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> {
return self.makeUnaryCall(path: "/MyGame.Example.MonsterStorage/Store", request: request, callOptions: callOptions ?? self.defaultCallOptions) return self.makeUnaryCall(path: "/MyGame.Example.MonsterStorage/Store", request: request, callOptions: callOptions ?? self.defaultCallOptions)
} }
public func Retrieve(_ request: Message<MyGame_Example_Stat>, callOptions: CallOptions? = nil, handler: @escaping (Message<MyGame_Example_Monster>) -> Void) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>> { public func Retrieve(_ request: Message<MyGame_Example_Stat>, callOptions: CallOptions? = nil, handler: @escaping (Message<MyGame_Example_Monster>) -> Void) -> ServerStreamingCall<Message<MyGame_Example_Stat>, Message<MyGame_Example_Monster>> {
return self.makeServerStreamingCall(path: "/MyGame.Example.MonsterStorage/Retrieve", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler) return self.makeServerStreamingCall(path: "/MyGame.Example.MonsterStorage/Retrieve", request: request, callOptions: callOptions ?? self.defaultCallOptions, handler: handler)
} }
public func GetMaxHitPoint(callOptions: CallOptions? = nil) -> ClientStreamingCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> { public func GetMaxHitPoint(callOptions: CallOptions? = nil) -> ClientStreamingCall<Message<MyGame_Example_Monster>,Message<MyGame_Example_Stat>> {
return self.makeClientStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", callOptions: callOptions ?? self.defaultCallOptions) return self.makeClientStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", callOptions: callOptions ?? self.defaultCallOptions)
} }
public func GetMinMaxHitPoints(callOptions: CallOptions? = nil, handler: @escaping (Message<MyGame_Example_Stat>) -> Void) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> { public func GetMinMaxHitPoints(callOptions: CallOptions? = nil, handler: @escaping (Message<MyGame_Example_Stat>) -> Void) -> BidirectionalStreamingCall<Message<MyGame_Example_Monster>, Message<MyGame_Example_Stat>> {
return self.makeBidirectionalStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", callOptions: callOptions ?? self.defaultCallOptions, handler: handler) return self.makeBidirectionalStreamingCall(path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", callOptions: callOptions ?? self.defaultCallOptions, handler: handler)
} }
} }
public protocol MyGame_Example_MonsterStorageProvider: CallHandlerProvider { public protocol MyGame_Example_MonsterStorageProvider: CallHandlerProvider {
func Store(_ request: Message<MyGame_Example_Monster>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<MyGame_Example_Stat>> func Store(_ request: Message<MyGame_Example_Monster>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<MyGame_Example_Stat>>
func Retrieve(request: Message<MyGame_Example_Stat>, context: StreamingResponseCallContext<Message<MyGame_Example_Monster>>) -> EventLoopFuture<GRPCStatus> func Retrieve(request: Message<MyGame_Example_Stat>, context: StreamingResponseCallContext<Message<MyGame_Example_Monster>>) -> EventLoopFuture<GRPCStatus>
func GetMaxHitPoint(context: UnaryResponseCallContext<Message<MyGame_Example_Stat>>) -> EventLoopFuture<(StreamEvent<Message<MyGame_Example_Monster>>) -> Void> func GetMaxHitPoint(context: UnaryResponseCallContext<Message<MyGame_Example_Stat>>) -> EventLoopFuture<(StreamEvent<Message<MyGame_Example_Monster>>) -> Void>
func GetMinMaxHitPoints(context: StreamingResponseCallContext<Message<MyGame_Example_Stat>>) -> EventLoopFuture<(StreamEvent<Message<MyGame_Example_Monster>>) -> Void> func GetMinMaxHitPoints(context: StreamingResponseCallContext<Message<MyGame_Example_Stat>>) -> EventLoopFuture<(StreamEvent<Message<MyGame_Example_Monster>>) -> Void>
} }
public extension MyGame_Example_MonsterStorageProvider { 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? { func handleMethod(_ methodName: Substring, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
switch methodName { switch methodName {
case "Store": case "Store":
return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
return { request in return { request in
self.Store(request, context: context) self.Store(request, context: context)
} }
} }
case "Retrieve": case "Retrieve":
return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in return CallHandlerFactory.makeServerStreaming(callHandlerContext: callHandlerContext) { context in
return { request in return { request in
self.Retrieve(request: request, context: context) self.Retrieve(request: request, context: context)
} }
} }
case "GetMaxHitPoint": case "GetMaxHitPoint":
return CallHandlerFactory.makeClientStreaming(callHandlerContext: callHandlerContext) { context in return CallHandlerFactory.makeClientStreaming(callHandlerContext: callHandlerContext) { context in
self.GetMaxHitPoint(context: context) self.GetMaxHitPoint(context: context)
} }
case "GetMinMaxHitPoints": case "GetMinMaxHitPoints":
return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in return CallHandlerFactory.makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in
self.GetMinMaxHitPoints(context: context) self.GetMinMaxHitPoints(context: context)
} }
default: return nil; default: return nil;
} }
} }
} }

View File

@@ -1,227 +1,228 @@
// automatically generated by the FlatBuffers compiler, do not modify // automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all // swiftlint:disable all
// swiftformat:disable all
import FlatBuffers import FlatBuffers
public enum optional_scalars_OptionalByte: Int8, Enum { public enum optional_scalars_OptionalByte: Int8, Enum {
public typealias T = Int8 public typealias T = Int8
public static var byteSize: Int { return MemoryLayout<Int8>.size } public static var byteSize: Int { return MemoryLayout<Int8>.size }
public var value: Int8 { return self.rawValue } public var value: Int8 { return self.rawValue }
case none_ = 0 case none_ = 0
case one = 1 case one = 1
case two = 2 case two = 2
public static var max: optional_scalars_OptionalByte { return .two } public static var max: optional_scalars_OptionalByte { return .two }
public static var min: optional_scalars_OptionalByte { return .none_ } public static var min: optional_scalars_OptionalByte { return .none_ }
} }
public struct optional_scalars_ScalarStuff: FlatBufferObject { public struct optional_scalars_ScalarStuff: FlatBufferObject {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table
public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "NULL", addPrefix: prefix) } public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, 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 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 } private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset { private enum VTOFFSET: VOffset {
case justI8 = 4 case justI8 = 4
case maybeI8 = 6 case maybeI8 = 6
case defaultI8 = 8 case defaultI8 = 8
case justU8 = 10 case justU8 = 10
case maybeU8 = 12 case maybeU8 = 12
case defaultU8 = 14 case defaultU8 = 14
case justI16 = 16 case justI16 = 16
case maybeI16 = 18 case maybeI16 = 18
case defaultI16 = 20 case defaultI16 = 20
case justU16 = 22 case justU16 = 22
case maybeU16 = 24 case maybeU16 = 24
case defaultU16 = 26 case defaultU16 = 26
case justI32 = 28 case justI32 = 28
case maybeI32 = 30 case maybeI32 = 30
case defaultI32 = 32 case defaultI32 = 32
case justU32 = 34 case justU32 = 34
case maybeU32 = 36 case maybeU32 = 36
case defaultU32 = 38 case defaultU32 = 38
case justI64 = 40 case justI64 = 40
case maybeI64 = 42 case maybeI64 = 42
case defaultI64 = 44 case defaultI64 = 44
case justU64 = 46 case justU64 = 46
case maybeU64 = 48 case maybeU64 = 48
case defaultU64 = 50 case defaultU64 = 50
case justF32 = 52 case justF32 = 52
case maybeF32 = 54 case maybeF32 = 54
case defaultF32 = 56 case defaultF32 = 56
case justF64 = 58 case justF64 = 58
case maybeF64 = 60 case maybeF64 = 60
case defaultF64 = 62 case defaultF64 = 62
case justBool = 64 case justBool = 64
case maybeBool = 66 case maybeBool = 66
case defaultBool = 68 case defaultBool = 68
case justEnum = 70 case justEnum = 70
case maybeEnum = 72 case maybeEnum = 72
case defaultEnum = 74 case defaultEnum = 74
var v: Int32 { Int32(self.rawValue) } var v: Int32 { Int32(self.rawValue) }
var p: VOffset { 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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(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, public static func add(justBool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justBool, def: false,
at: VTOFFSET.justBool.p) } 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(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, public static func add(defaultBool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultBool, def: true,
at: VTOFFSET.defaultBool.p) } 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(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(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 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<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } public static func endScalarStuff(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createScalarStuff( public static func createScalarStuff(
_ fbb: inout FlatBufferBuilder, _ fbb: inout FlatBufferBuilder,
justI8: Int8 = 0, justI8: Int8 = 0,
maybeI8: Int8? = nil, maybeI8: Int8? = nil,
defaultI8: Int8 = 42, defaultI8: Int8 = 42,
justU8: UInt8 = 0, justU8: UInt8 = 0,
maybeU8: UInt8? = nil, maybeU8: UInt8? = nil,
defaultU8: UInt8 = 42, defaultU8: UInt8 = 42,
justI16: Int16 = 0, justI16: Int16 = 0,
maybeI16: Int16? = nil, maybeI16: Int16? = nil,
defaultI16: Int16 = 42, defaultI16: Int16 = 42,
justU16: UInt16 = 0, justU16: UInt16 = 0,
maybeU16: UInt16? = nil, maybeU16: UInt16? = nil,
defaultU16: UInt16 = 42, defaultU16: UInt16 = 42,
justI32: Int32 = 0, justI32: Int32 = 0,
maybeI32: Int32? = nil, maybeI32: Int32? = nil,
defaultI32: Int32 = 42, defaultI32: Int32 = 42,
justU32: UInt32 = 0, justU32: UInt32 = 0,
maybeU32: UInt32? = nil, maybeU32: UInt32? = nil,
defaultU32: UInt32 = 42, defaultU32: UInt32 = 42,
justI64: Int64 = 0, justI64: Int64 = 0,
maybeI64: Int64? = nil, maybeI64: Int64? = nil,
defaultI64: Int64 = 42, defaultI64: Int64 = 42,
justU64: UInt64 = 0, justU64: UInt64 = 0,
maybeU64: UInt64? = nil, maybeU64: UInt64? = nil,
defaultU64: UInt64 = 42, defaultU64: UInt64 = 42,
justF32: Float32 = 0.0, justF32: Float32 = 0.0,
maybeF32: Float32? = nil, maybeF32: Float32? = nil,
defaultF32: Float32 = 42.0, defaultF32: Float32 = 42.0,
justF64: Double = 0.0, justF64: Double = 0.0,
maybeF64: Double? = nil, maybeF64: Double? = nil,
defaultF64: Double = 42.0, defaultF64: Double = 42.0,
justBool: Bool = false, justBool: Bool = false,
maybeBool: Bool? = nil, maybeBool: Bool? = nil,
defaultBool: Bool = true, defaultBool: Bool = true,
justEnum: optional_scalars_OptionalByte = .none_, justEnum: optional_scalars_OptionalByte = .none_,
maybeEnum: optional_scalars_OptionalByte? = nil, maybeEnum: optional_scalars_OptionalByte? = nil,
defaultEnum: optional_scalars_OptionalByte = .one defaultEnum: optional_scalars_OptionalByte = .one
) -> Offset<UOffset> { ) -> Offset<UOffset> {
let __start = optional_scalars_ScalarStuff.startScalarStuff(&fbb) let __start = optional_scalars_ScalarStuff.startScalarStuff(&fbb)
optional_scalars_ScalarStuff.add(justI8: justI8, &fbb) optional_scalars_ScalarStuff.add(justI8: justI8, &fbb)
optional_scalars_ScalarStuff.add(maybeI8: maybeI8, &fbb) optional_scalars_ScalarStuff.add(maybeI8: maybeI8, &fbb)
optional_scalars_ScalarStuff.add(defaultI8: defaultI8, &fbb) optional_scalars_ScalarStuff.add(defaultI8: defaultI8, &fbb)
optional_scalars_ScalarStuff.add(justU8: justU8, &fbb) optional_scalars_ScalarStuff.add(justU8: justU8, &fbb)
optional_scalars_ScalarStuff.add(maybeU8: maybeU8, &fbb) optional_scalars_ScalarStuff.add(maybeU8: maybeU8, &fbb)
optional_scalars_ScalarStuff.add(defaultU8: defaultU8, &fbb) optional_scalars_ScalarStuff.add(defaultU8: defaultU8, &fbb)
optional_scalars_ScalarStuff.add(justI16: justI16, &fbb) optional_scalars_ScalarStuff.add(justI16: justI16, &fbb)
optional_scalars_ScalarStuff.add(maybeI16: maybeI16, &fbb) optional_scalars_ScalarStuff.add(maybeI16: maybeI16, &fbb)
optional_scalars_ScalarStuff.add(defaultI16: defaultI16, &fbb) optional_scalars_ScalarStuff.add(defaultI16: defaultI16, &fbb)
optional_scalars_ScalarStuff.add(justU16: justU16, &fbb) optional_scalars_ScalarStuff.add(justU16: justU16, &fbb)
optional_scalars_ScalarStuff.add(maybeU16: maybeU16, &fbb) optional_scalars_ScalarStuff.add(maybeU16: maybeU16, &fbb)
optional_scalars_ScalarStuff.add(defaultU16: defaultU16, &fbb) optional_scalars_ScalarStuff.add(defaultU16: defaultU16, &fbb)
optional_scalars_ScalarStuff.add(justI32: justI32, &fbb) optional_scalars_ScalarStuff.add(justI32: justI32, &fbb)
optional_scalars_ScalarStuff.add(maybeI32: maybeI32, &fbb) optional_scalars_ScalarStuff.add(maybeI32: maybeI32, &fbb)
optional_scalars_ScalarStuff.add(defaultI32: defaultI32, &fbb) optional_scalars_ScalarStuff.add(defaultI32: defaultI32, &fbb)
optional_scalars_ScalarStuff.add(justU32: justU32, &fbb) optional_scalars_ScalarStuff.add(justU32: justU32, &fbb)
optional_scalars_ScalarStuff.add(maybeU32: maybeU32, &fbb) optional_scalars_ScalarStuff.add(maybeU32: maybeU32, &fbb)
optional_scalars_ScalarStuff.add(defaultU32: defaultU32, &fbb) optional_scalars_ScalarStuff.add(defaultU32: defaultU32, &fbb)
optional_scalars_ScalarStuff.add(justI64: justI64, &fbb) optional_scalars_ScalarStuff.add(justI64: justI64, &fbb)
optional_scalars_ScalarStuff.add(maybeI64: maybeI64, &fbb) optional_scalars_ScalarStuff.add(maybeI64: maybeI64, &fbb)
optional_scalars_ScalarStuff.add(defaultI64: defaultI64, &fbb) optional_scalars_ScalarStuff.add(defaultI64: defaultI64, &fbb)
optional_scalars_ScalarStuff.add(justU64: justU64, &fbb) optional_scalars_ScalarStuff.add(justU64: justU64, &fbb)
optional_scalars_ScalarStuff.add(maybeU64: maybeU64, &fbb) optional_scalars_ScalarStuff.add(maybeU64: maybeU64, &fbb)
optional_scalars_ScalarStuff.add(defaultU64: defaultU64, &fbb) optional_scalars_ScalarStuff.add(defaultU64: defaultU64, &fbb)
optional_scalars_ScalarStuff.add(justF32: justF32, &fbb) optional_scalars_ScalarStuff.add(justF32: justF32, &fbb)
optional_scalars_ScalarStuff.add(maybeF32: maybeF32, &fbb) optional_scalars_ScalarStuff.add(maybeF32: maybeF32, &fbb)
optional_scalars_ScalarStuff.add(defaultF32: defaultF32, &fbb) optional_scalars_ScalarStuff.add(defaultF32: defaultF32, &fbb)
optional_scalars_ScalarStuff.add(justF64: justF64, &fbb) optional_scalars_ScalarStuff.add(justF64: justF64, &fbb)
optional_scalars_ScalarStuff.add(maybeF64: maybeF64, &fbb) optional_scalars_ScalarStuff.add(maybeF64: maybeF64, &fbb)
optional_scalars_ScalarStuff.add(defaultF64: defaultF64, &fbb) optional_scalars_ScalarStuff.add(defaultF64: defaultF64, &fbb)
optional_scalars_ScalarStuff.add(justBool: justBool, &fbb) optional_scalars_ScalarStuff.add(justBool: justBool, &fbb)
optional_scalars_ScalarStuff.add(maybeBool: maybeBool, &fbb) optional_scalars_ScalarStuff.add(maybeBool: maybeBool, &fbb)
optional_scalars_ScalarStuff.add(defaultBool: defaultBool, &fbb) optional_scalars_ScalarStuff.add(defaultBool: defaultBool, &fbb)
optional_scalars_ScalarStuff.add(justEnum: justEnum, &fbb) optional_scalars_ScalarStuff.add(justEnum: justEnum, &fbb)
optional_scalars_ScalarStuff.add(maybeEnum: maybeEnum, &fbb) optional_scalars_ScalarStuff.add(maybeEnum: maybeEnum, &fbb)
optional_scalars_ScalarStuff.add(defaultEnum: defaultEnum, &fbb) optional_scalars_ScalarStuff.add(defaultEnum: defaultEnum, &fbb)
return optional_scalars_ScalarStuff.endScalarStuff(&fbb, start: __start) return optional_scalars_ScalarStuff.endScalarStuff(&fbb, start: __start)
} }
} }

View File

@@ -1,336 +1,337 @@
// automatically generated by the FlatBuffers compiler, do not modify // automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all // swiftlint:disable all
// swiftformat:disable all
import FlatBuffers import FlatBuffers
public enum Character: UInt8, Enum { public enum Character: UInt8, Enum {
public typealias T = UInt8 public typealias T = UInt8
public static var byteSize: Int { return MemoryLayout<UInt8>.size } public static var byteSize: Int { return MemoryLayout<UInt8>.size }
public var value: UInt8 { return self.rawValue } public var value: UInt8 { return self.rawValue }
case none_ = 0 case none_ = 0
case mulan = 1 case mulan = 1
case rapunzel = 2 case rapunzel = 2
case belle = 3 case belle = 3
case bookfan = 4 case bookfan = 4
case other = 5 case other = 5
case unused = 6 case unused = 6
public static var max: Character { return .unused } public static var max: Character { return .unused }
public static var min: Character { return .none_ } public static var min: Character { return .none_ }
} }
public struct CharacterUnion { public struct CharacterUnion {
public var type: Character public var type: Character
public var value: NativeTable? public var value: NativeTable?
public init(_ v: NativeTable?, type: Character) { public init(_ v: NativeTable?, type: Character) {
self.type = type self.type = type
self.value = v self.value = v
} }
public func pack(builder: inout FlatBufferBuilder) -> Offset<UOffset> { public func pack(builder: inout FlatBufferBuilder) -> Offset<UOffset> {
switch type { switch type {
case .mulan: case .mulan:
var __obj = value as? AttackerT var __obj = value as? AttackerT
return Attacker.pack(&builder, obj: &__obj) return Attacker.pack(&builder, obj: &__obj)
case .rapunzel: case .rapunzel:
var __obj = value as? RapunzelT var __obj = value as? RapunzelT
return Rapunzel.pack(&builder, obj: &__obj) return Rapunzel.pack(&builder, obj: &__obj)
case .belle: case .belle:
var __obj = value as? BookReaderT var __obj = value as? BookReaderT
return BookReader.pack(&builder, obj: &__obj) return BookReader.pack(&builder, obj: &__obj)
case .bookfan: case .bookfan:
var __obj = value as? BookReaderT var __obj = value as? BookReaderT
return BookReader.pack(&builder, obj: &__obj) return BookReader.pack(&builder, obj: &__obj)
default: return Offset() default: return Offset()
}
} }
}
} }
public struct Rapunzel: Readable { public struct Rapunzel: Readable {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct private var _accessor: Struct
public static var size = 4 public static var size = 4
public static var alignment = 4 public static var alignment = 4
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var hairLength: Int32 { return _accessor.readBuffer(of: Int32.self, at: 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) } @discardableResult public func mutate(hairLength: Int32) -> Bool { return _accessor.mutate(hairLength, index: 0) }
public mutating func unpack() -> RapunzelT { public mutating func unpack() -> RapunzelT {
return RapunzelT(&self) return RapunzelT(&self)
} }
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT?) -> Offset<UOffset> { public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT?) -> Offset<UOffset> {
guard var obj = obj else { return Offset<UOffset>() } guard var obj = obj else { return Offset<UOffset>() }
return pack(&builder, obj: &obj) return pack(&builder, obj: &obj)
} }
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT) -> Offset<UOffset> { public static func pack(_ builder: inout FlatBufferBuilder, obj: inout RapunzelT) -> Offset<UOffset> {
return createRapunzel(builder: &builder, hairLength: obj.hairLength) return createRapunzel(builder: &builder, hairLength: obj.hairLength)
} }
} }
public class RapunzelT: NativeTable { public class RapunzelT: NativeTable {
public var hairLength: Int32 public var hairLength: Int32
public init(_ _t: inout Rapunzel) { public init(_ _t: inout Rapunzel) {
hairLength = _t.hairLength hairLength = _t.hairLength
} }
public init() { public init() {
hairLength = 0 hairLength = 0
} }
} }
public struct BookReader: Readable { public struct BookReader: Readable {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Struct private var _accessor: Struct
public static var size = 4 public static var size = 4
public static var alignment = 4 public static var alignment = 4
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
public var booksRead: Int32 { return _accessor.readBuffer(of: Int32.self, at: 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) } @discardableResult public func mutate(booksRead: Int32) -> Bool { return _accessor.mutate(booksRead, index: 0) }
public mutating func unpack() -> BookReaderT { public mutating func unpack() -> BookReaderT {
return BookReaderT(&self) return BookReaderT(&self)
} }
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT?) -> Offset<UOffset> { public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT?) -> Offset<UOffset> {
guard var obj = obj else { return Offset<UOffset>() } guard var obj = obj else { return Offset<UOffset>() }
return pack(&builder, obj: &obj) return pack(&builder, obj: &obj)
} }
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT) -> Offset<UOffset> { public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReaderT) -> Offset<UOffset> {
return createBookReader(builder: &builder, booksRead: obj.booksRead) return createBookReader(builder: &builder, booksRead: obj.booksRead)
} }
} }
public class BookReaderT: NativeTable { public class BookReaderT: NativeTable {
public var booksRead: Int32 public var booksRead: Int32
public init(_ _t: inout BookReader) { public init(_ _t: inout BookReader) {
booksRead = _t.booksRead booksRead = _t.booksRead
} }
public init() { public init() {
booksRead = 0 booksRead = 0
} }
} }
extension Rapunzel { extension Rapunzel {
@discardableResult @discardableResult
public static func createRapunzel(builder: inout FlatBufferBuilder, hairLength: Int32 = 0) -> Offset<UOffset> { public static func createRapunzel(builder: inout FlatBufferBuilder, hairLength: Int32 = 0) -> Offset<UOffset> {
builder.createStructOf(size: Rapunzel.size, alignment: Rapunzel.alignment) builder.createStructOf(size: Rapunzel.size, alignment: Rapunzel.alignment)
builder.reverseAdd(v: hairLength, postion: 0) builder.reverseAdd(v: hairLength, postion: 0)
return builder.endStruct() return builder.endStruct()
} }
} }
extension BookReader { extension BookReader {
@discardableResult @discardableResult
public static func createBookReader(builder: inout FlatBufferBuilder, booksRead: Int32 = 0) -> Offset<UOffset> { public static func createBookReader(builder: inout FlatBufferBuilder, booksRead: Int32 = 0) -> Offset<UOffset> {
builder.createStructOf(size: BookReader.size, alignment: BookReader.alignment) builder.createStructOf(size: BookReader.size, alignment: BookReader.alignment)
builder.reverseAdd(v: booksRead, postion: 0) builder.reverseAdd(v: booksRead, postion: 0)
return builder.endStruct() return builder.endStruct()
} }
} }
public struct Attacker: FlatBufferObject, ObjectAPI { public struct Attacker: FlatBufferObject, ObjectAPI {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table
public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) } public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, 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 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 } private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset { private enum VTOFFSET: VOffset {
case swordAttackDamage = 4 case swordAttackDamage = 4
var v: Int32 { Int32(self.rawValue) } var v: Int32 { Int32(self.rawValue) }
var p: VOffset { 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) } 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) } @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 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 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<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end } public static func endAttacker(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createAttacker( public static func createAttacker(
_ fbb: inout FlatBufferBuilder, _ fbb: inout FlatBufferBuilder,
swordAttackDamage: Int32 = 0 swordAttackDamage: Int32 = 0
) -> Offset<UOffset> { ) -> Offset<UOffset> {
let __start = Attacker.startAttacker(&fbb) let __start = Attacker.startAttacker(&fbb)
Attacker.add(swordAttackDamage: swordAttackDamage, &fbb) Attacker.add(swordAttackDamage: swordAttackDamage, &fbb)
return Attacker.endAttacker(&fbb, start: __start) return Attacker.endAttacker(&fbb, start: __start)
} }
public mutating func unpack() -> AttackerT { public mutating func unpack() -> AttackerT {
return AttackerT(&self) return AttackerT(&self)
} }
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT?) -> Offset<UOffset> { public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT?) -> Offset<UOffset> {
guard var obj = obj else { return Offset<UOffset>() } guard var obj = obj else { return Offset<UOffset>() }
return pack(&builder, obj: &obj) return pack(&builder, obj: &obj)
} }
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT) -> Offset<UOffset> { public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT) -> Offset<UOffset> {
let __root = Attacker.startAttacker(&builder) let __root = Attacker.startAttacker(&builder)
Attacker.add(swordAttackDamage: obj.swordAttackDamage, &builder) Attacker.add(swordAttackDamage: obj.swordAttackDamage, &builder)
return Attacker.endAttacker(&builder, start: __root) return Attacker.endAttacker(&builder, start: __root)
} }
} }
public class AttackerT: NativeTable { public class AttackerT: NativeTable {
public var swordAttackDamage: Int32 public var swordAttackDamage: Int32
public init(_ _t: inout Attacker) { public init(_ _t: inout Attacker) {
swordAttackDamage = _t.swordAttackDamage swordAttackDamage = _t.swordAttackDamage
} }
public init() { public init() {
swordAttackDamage = 0 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 { public struct Movie: FlatBufferObject, ObjectAPI {
static func validateVersion() { FlatBuffersVersion_1_12_0() } static func validateVersion() { FlatBuffersVersion_1_12_0() }
public var __buffer: ByteBuffer! { return _accessor.bb } public var __buffer: ByteBuffer! { return _accessor.bb }
private var _accessor: Table private var _accessor: Table
public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, prefix: Bool = false) { fbb.finish(offset: end, fileId: "MOVI", addPrefix: prefix) } public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset<UOffset>, 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 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 } private init(_ t: Table) { _accessor = t }
public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
private enum VTOFFSET: VOffset { private enum VTOFFSET: VOffset {
case mainCharacterType = 4 case mainCharacterType = 4
case mainCharacter = 6 case mainCharacter = 6
case charactersType = 8 case charactersType = 8
case characters = 10 case characters = 10
var v: Int32 { Int32(self.rawValue) } var v: Int32 { Int32(self.rawValue) }
var p: VOffset { 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<T: FlatBufferObject>(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<T: FlatBufferObject>(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<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VTOFFSET.mainCharacter.p) }
public static func addVectorOf(charactersType: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VTOFFSET.charactersType.p) }
public static func addVectorOf(characters: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VTOFFSET.characters.p) }
public static func endMovie(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createMovie(
_ fbb: inout FlatBufferBuilder,
mainCharacterType: Character = .none_,
offsetOfMainCharacter mainCharacter: Offset<UOffset> = Offset(),
vectorOfCharactersType charactersType: Offset<UOffset> = Offset(),
vectorOfCharacters characters: Offset<UOffset> = Offset()
) -> Offset<UOffset> {
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<UOffset> {
guard var obj = obj else { return Offset<UOffset>() }
return pack(&builder, obj: &obj)
}
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT) -> Offset<UOffset> {
let __mainCharacter = obj.mainCharacter?.pack(builder: &builder) ?? Offset()
var __characters__: [Offset<UOffset>] = []
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_ } Movie.addVectorOf(charactersType: __charactersType, &builder)
public func mainCharacter<T: FlatBufferObject>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.mainCharacter.v); return o == 0 ? nil : _accessor.union(o) } Movie.addVectorOf(characters: __characters, &builder)
public var charactersTypeCount: Int32 { let o = _accessor.offset(VTOFFSET.charactersType.v); return o == 0 ? 0 : _accessor.vector(count: o) } return Movie.endMovie(&builder, start: __root)
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<T: FlatBufferObject>(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<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VTOFFSET.mainCharacter.p) }
public static func addVectorOf(charactersType: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VTOFFSET.charactersType.p) }
public static func addVectorOf(characters: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VTOFFSET.characters.p) }
public static func endMovie(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
public static func createMovie(
_ fbb: inout FlatBufferBuilder,
mainCharacterType: Character = .none_,
offsetOfMainCharacter mainCharacter: Offset<UOffset> = Offset(),
vectorOfCharactersType charactersType: Offset<UOffset> = Offset(),
vectorOfCharacters characters: Offset<UOffset> = Offset()
) -> Offset<UOffset> {
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<UOffset> {
guard var obj = obj else { return Offset<UOffset>() }
return pack(&builder, obj: &obj)
}
public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT) -> Offset<UOffset> {
let __mainCharacter = obj.mainCharacter?.pack(builder: &builder) ?? Offset()
var __characters__: [Offset<UOffset>] = []
for i in obj.characters {
guard let off = i?.pack(builder: &builder) else { continue }
__characters__.append(off)
}
let __characters = builder.createVector(ofOffsets: __characters__)
let __charactersType = builder.createVector(obj.characters.compactMap { $0?.type })
let __root = Movie.startMovie(&builder)
if let o = obj.mainCharacter?.type {
Movie.add(mainCharacterType: o, &builder)
Movie.add(mainCharacter: __mainCharacter, &builder)
}
Movie.addVectorOf(charactersType: __charactersType, &builder)
Movie.addVectorOf(characters: __characters, &builder)
return Movie.endMovie(&builder, start: __root)
}
} }
public class MovieT: NativeTable { public class MovieT: NativeTable {
public var mainCharacter: CharacterUnion? public var mainCharacter: CharacterUnion?
public var characters: [CharacterUnion?] public var characters: [CharacterUnion?]
public init(_ _t: inout Movie) { public init(_ _t: inout Movie) {
switch _t.mainCharacterType { 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: case .mulan:
var _v = _t.mainCharacter(type: Attacker.self) var _v = _t.characters(at: index, type: Attacker.self)
mainCharacter = CharacterUnion(_v?.unpack(), type: .mulan) characters.append(CharacterUnion(_v?.unpack(), type: .mulan))
case .rapunzel: case .rapunzel:
var _v = _t.mainCharacter(type: Rapunzel.self) var _v = _t.characters(at: index, type: Rapunzel.self)
mainCharacter = CharacterUnion(_v?.unpack(), type: .rapunzel) characters.append(CharacterUnion(_v?.unpack(), type: .rapunzel))
case .belle: case .belle:
var _v = _t.mainCharacter(type: BookReader.self) var _v = _t.characters(at: index, type: BookReader.self)
mainCharacter = CharacterUnion(_v?.unpack(), type: .belle) characters.append(CharacterUnion(_v?.unpack(), type: .belle))
case .bookfan: case .bookfan:
var _v = _t.mainCharacter(type: BookReader.self) var _v = _t.characters(at: index, type: BookReader.self)
mainCharacter = CharacterUnion(_v?.unpack(), type: .bookfan) characters.append(CharacterUnion(_v?.unpack(), type: .bookfan))
default: break 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() { public init() {
characters = [] characters = []
} }
public func serialize() -> ByteBuffer { return serialize(type: Movie.self) } public func serialize() -> ByteBuffer { return serialize(type: Movie.self) }
} }

View File

@@ -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 XCTest
import FlatBuffers_Test_SwiftTests import FlatBuffers_Test_SwiftTests