[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";

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
@@ -30,7 +45,8 @@ func main() {
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(
&builder,
structOfPos: pos, structOfPos: pos,
hp: 300, hp: 300,
offsetOfName: name, offsetOfName: name,

View File

@@ -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,5 +1,19 @@
// 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
@@ -18,5 +32,4 @@ let package = Package(
.target( .target(
name: "FlatBuffers", name: "FlatBuffers",
dependencies: []), dependencies: []),
] ])
)

View File

@@ -1,10 +1,27 @@
/*
* 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
final class Storage {
// This storage doesn't own the memory, therefore, we won't deallocate on deinit. // This storage doesn't own the memory, therefore, we won't deallocate on deinit.
private let unowned: Bool private let unowned: Bool
/// pointer to the start of the buffer object in memory /// pointer to the start of the buffer object in memory
@@ -31,18 +48,23 @@ public struct ByteBuffer {
} }
func copy(from ptr: UnsafeRawPointer, count: Int) { func copy(from ptr: UnsafeRawPointer, count: Int) {
assert(!unowned, "copy should NOT be called on a buffer that is built by assumingMemoryBound") assert(
!unowned,
"copy should NOT be called on a buffer that is built by assumingMemoryBound")
memory.copyMemory(from: ptr, byteCount: count) memory.copyMemory(from: ptr, byteCount: count)
} }
func initialize(for size: Int) { func initialize(for size: Int) {
assert(!unowned, "initalize should NOT be called on a buffer that is built by assumingMemoryBound") assert(
!unowned,
"initalize should NOT be called on a buffer that is built by assumingMemoryBound")
memset(memory, 0, size) memset(memory, 0, size)
} }
/// Reallocates the buffer incase the object to be written doesnt fit in the current buffer /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer
/// - Parameter size: Size of the current object /// - Parameter size: Size of the current object
@usableFromInline internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) { @usableFromInline
internal func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
let currentWritingIndex = capacity &- writerSize let currentWritingIndex = capacity &- writerSize
while capacity <= writerSize &+ size { while capacity <= writerSize &+ size {
capacity = capacity << 1 capacity = capacity << 1
@@ -53,7 +75,10 @@ public struct ByteBuffer {
let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment) let newData = UnsafeMutableRawPointer.allocate(byteCount: capacity, alignment: alignment)
memset(newData, 0, capacity &- writerSize) memset(newData, 0, capacity &- writerSize)
memcpy(newData.advanced(by: capacity &- writerSize), memory.advanced(by: currentWritingIndex), writerSize) memcpy(
newData.advanced(by: capacity &- writerSize),
memory.advanced(by: currentWritingIndex),
writerSize)
memory.deallocate() memory.deallocate()
memory = newData memory = newData
} }
@@ -66,16 +91,16 @@ public struct ByteBuffer {
/// Aliginment of the current memory being written to the buffer /// Aliginment of the current memory being written to the buffer
internal var alignment = 1 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 /// 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 } internal var writerIndex: Int { _storage.capacity &- _writerSize }
/// Reader is the position of the current Writer Index (capacity - size) /// Reader is the position of the current Writer Index (capacity - size)
public var reader: Int { return writerIndex } public var reader: Int { writerIndex }
/// Current size of the buffer /// Current size of the buffer
public var size: UOffset { return UOffset(_writerSize) } public var size: UOffset { UOffset(_writerSize) }
/// Public Pointer to the buffer object in memory. This should NOT be modified for any reason /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason
public var memory: UnsafeMutableRawPointer { return _storage.memory } public var memory: UnsafeMutableRawPointer { _storage.memory }
/// Current capacity for the buffer /// Current capacity for the buffer
public var capacity: Int { return _storage.capacity } public var capacity: Int { _storage.capacity }
/// Constructor that creates a Flatbuffer object from a UInt8 /// Constructor that creates a Flatbuffer object from a UInt8
/// - Parameter bytes: Array of UInt8 /// - Parameter bytes: Array of UInt8
@@ -114,8 +139,8 @@ public struct ByteBuffer {
/// - count: amount of readable bytes /// - count: amount of readable bytes
public init<Bytes: ContiguousBytes>( public init<Bytes: ContiguousBytes>(
contiguousBytes: Bytes, contiguousBytes: Bytes,
count: Int count: Int)
) { {
_storage = Storage(count: count, alignment: alignment) _storage = Storage(count: count, alignment: alignment)
_writerSize = _storage.capacity _writerSize = _storage.capacity
contiguousBytes.withUnsafeBytes { buf in contiguousBytes.withUnsafeBytes { buf in
@@ -155,7 +180,8 @@ public struct ByteBuffer {
/// Fills the buffer with padding by adding to the writersize /// Fills the buffer with padding by adding to the writersize
/// - Parameter padding: Amount of padding between two to be serialized objects /// - Parameter padding: Amount of padding between two to be serialized objects
@usableFromInline mutating func fill(padding: Int) { @usableFromInline
mutating func fill(padding: Int) {
assert(padding >= 0, "Fill should be larger than or equal to zero") assert(padding >= 0, "Fill should be larger than or equal to zero")
ensureSpace(size: padding) ensureSpace(size: padding)
_writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding) _writerSize = _writerSize &+ (MemoryLayout<UInt8>.size &* padding)
@@ -163,10 +189,11 @@ public struct ByteBuffer {
///Adds an array of type Scalar to the buffer memory ///Adds an array of type Scalar to the buffer memory
/// - Parameter elements: An array of Scalars /// - Parameter elements: An array of Scalars
@usableFromInline mutating func push<T: Scalar>(elements: [T]) { @usableFromInline
mutating func push<T: Scalar>(elements: [T]) {
let size = elements.count &* MemoryLayout<T>.size let size = elements.count &* MemoryLayout<T>.size
ensureSpace(size: size) ensureSpace(size: size)
elements.reversed().forEach { (s) in elements.reversed().forEach { s in
push(value: s, len: MemoryLayout.size(ofValue: s)) push(value: s, len: MemoryLayout.size(ofValue: s))
} }
} }
@@ -175,8 +202,12 @@ public struct ByteBuffer {
/// - Parameters: /// - Parameters:
/// - value: Pointer to the object in memory /// - value: Pointer to the object in memory
/// - size: Size of Value being written to the buffer /// - size: Size of Value being written to the buffer
@available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") @available(
@usableFromInline mutating func push(struct value: UnsafeMutableRawPointer, size: Int) { *,
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) ensureSpace(size: size)
memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size) memcpy(_storage.memory.advanced(by: writerIndex &- size), value, size)
defer { value.deallocate() } defer { value.deallocate() }
@@ -186,7 +217,8 @@ public struct ByteBuffer {
/// Prepares the buffer to receive a struct of certian size. /// Prepares the buffer to receive a struct of certian size.
/// The alignment of the memory is already handled since we already called preAlign /// The alignment of the memory is already handled since we already called preAlign
/// - Parameter size: size of the struct /// - Parameter size: size of the struct
@usableFromInline mutating func prepareBufferToReceiveStruct(of size: Int) { @usableFromInline
mutating func prepareBufferToReceiveStruct(of size: Int) {
ensureSpace(size: size) ensureSpace(size: size)
_writerSize = _writerSize &+ size _writerSize = _writerSize &+ size
} }
@@ -197,7 +229,8 @@ public struct ByteBuffer {
/// - value: value of type Scalar /// - value: value of type Scalar
/// - position: position relative to the `writerIndex` /// - position: position relative to the `writerIndex`
/// - len: length of the value in terms of bytes /// - len: length of the value in terms of bytes
@usableFromInline mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) { @usableFromInline
mutating func reversePush<T: Scalar>(value: T, position: Int, len: Int) {
var v = value var v = value
memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len) memcpy(_storage.memory.advanced(by: writerIndex &+ position), &v, len)
} }
@@ -206,7 +239,8 @@ public struct ByteBuffer {
/// - Parameters: /// - Parameters:
/// - value: Object that will be written to the buffer /// - value: Object that will be written to the buffer
/// - len: Offset to subtract from the WriterIndex /// - len: Offset to subtract from the WriterIndex
@usableFromInline mutating func push<T: Scalar>(value: T, len: Int) { @usableFromInline
mutating func push<T: Scalar>(value: T, len: Int) {
ensureSpace(size: len) ensureSpace(size: len)
var v = value var v = value
memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len) memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len)
@@ -216,7 +250,8 @@ public struct ByteBuffer {
/// Adds a string to the buffer using swift.utf8 object /// Adds a string to the buffer using swift.utf8 object
/// - Parameter str: String that will be added to the buffer /// - Parameter str: String that will be added to the buffer
/// - Parameter len: length of the string /// - Parameter len: length of the string
@usableFromInline mutating func push(string str: String, len: Int) { @usableFromInline
mutating func push(string str: String, len: Int) {
ensureSpace(size: len) ensureSpace(size: len)
if str.utf8.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != nil { if str.utf8.withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != nil {
} else { } else {
@@ -231,8 +266,15 @@ public struct ByteBuffer {
/// - Parameters: /// - Parameters:
/// - bytes: Pointer to the view /// - bytes: Pointer to the view
/// - len: Size of string /// - len: Size of string
@usableFromInline mutating internal func push(bytes: UnsafeBufferPointer<String.UTF8View.Element>, len: Int) -> Bool { @usableFromInline
memcpy(_storage.memory.advanced(by: writerIndex &- len), UnsafeRawPointer(bytes.baseAddress!), len) 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 _writerSize = _writerSize &+ len
return true return true
} }
@@ -258,7 +300,8 @@ public struct ByteBuffer {
/// Makes sure that buffer has enouch space for each of the objects that will be written into it /// Makes sure that buffer has enouch space for each of the objects that will be written into it
/// - Parameter size: size of object /// - Parameter size: size of object
@discardableResult @discardableResult
@usableFromInline mutating func ensureSpace(size: Int) -> Int { @usableFromInline
mutating func ensureSpace(size: Int) -> Int {
if size &+ _writerSize > _storage.capacity { if size &+ _writerSize > _storage.capacity {
_storage.reallocate(size, writerSize: _writerSize, alignment: alignment) _storage.reallocate(size, writerSize: _writerSize, alignment: alignment)
} }
@@ -268,7 +311,8 @@ public struct ByteBuffer {
/// pops the written VTable if it's already written into the buffer /// pops the written VTable if it's already written into the buffer
/// - Parameter size: size of the `VTable` /// - Parameter size: size of the `VTable`
@usableFromInline mutating internal func pop(_ size: Int) { @usableFromInline
mutating internal func pop(_ size: Int) {
assert((_writerSize &- size) > 0, "New size should NOT be a negative number") assert((_writerSize &- size) > 0, "New size should NOT be a negative number")
memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size) memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size)
_writerSize = size _writerSize = size
@@ -291,7 +335,9 @@ public struct ByteBuffer {
/// - def: Type of the object /// - def: Type of the object
/// - position: the index of the object in the buffer /// - position: the index of the object in the buffer
public func read<T>(def: T.Type, position: Int) -> T { public func read<T>(def: T.Type, position: Int) -> T {
assert(position + MemoryLayout<T>.size <= _storage.capacity, "Reading out of bounds is illegal") assert(
position + MemoryLayout<T>.size <= _storage.capacity,
"Reading out of bounds is illegal")
return _storage.memory.advanced(by: position).load(as: T.self) return _storage.memory.advanced(by: position).load(as: T.self)
} }
@@ -299,8 +345,10 @@ public struct ByteBuffer {
/// - Parameters: /// - Parameters:
/// - index: index of the object to be read from the buffer /// - index: index of the object to be read from the buffer
/// - count: count of bytes in memory /// - count: count of bytes in memory
public func readSlice<T>(index: Int32, public func readSlice<T>(
count: Int32) -> [T] { index: Int32,
count: Int32) -> [T]
{
let _index = Int(index) let _index = Int(index)
let _count = Int(count) let _count = Int(count)
assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal") assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal")
@@ -314,9 +362,11 @@ public struct ByteBuffer {
/// - index: index of the string in the buffer /// - index: index of the string in the buffer
/// - count: length of the string /// - count: length of the string
/// - type: Encoding of the string /// - type: Encoding of the string
public func readString(at index: Int32, public func readString(
at index: Int32,
count: Int32, count: Int32,
type: String.Encoding = .utf8) -> String? { type: String.Encoding = .utf8) -> String?
{
let _index = Int(index) let _index = Int(index)
let _count = Int(count) let _count = Int(count)
assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal") assert(_index + _count <= _storage.capacity, "Reading out of bounds is illegal")
@@ -330,7 +380,10 @@ public struct ByteBuffer {
public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer { public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer {
assert(removeBytes > 0, "Can NOT remove negative bytes") assert(removeBytes > 0, "Can NOT remove negative bytes")
assert(removeBytes < _storage.capacity, "Can NOT remove more bytes than the ones allocated") assert(removeBytes < _storage.capacity, "Can NOT remove more bytes than the ones allocated")
return ByteBuffer(memory: _storage.memory, count: _storage.capacity, removing: _writerSize &- removeBytes) return ByteBuffer(
memory: _storage.memory,
count: _storage.capacity,
removing: _writerSize &- removeBytes)
} }
} }

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
@@ -29,7 +45,7 @@ extension Scalar where Self: FixedWidthInteger {
/// ///
/// 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
} }
} }
@@ -37,7 +53,7 @@ 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
} }
} }
@@ -45,13 +61,13 @@ 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

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 Foundation import Foundation
public struct FlatBufferBuilder { public struct FlatBufferBuilder {
@@ -26,16 +42,18 @@ public struct FlatBufferBuilder {
} }
/// Gives a read access to the buffer's size /// Gives a read access to the buffer's size
public var size: UOffset { return _bb.size } public var size: UOffset { _bb.size }
/// Data representation of the buffer /// Data representation of the buffer
public var data: Data { public var data: Data {
assert(finished, "Data shouldn't be called before finish()") assert(finished, "Data shouldn't be called before finish()")
return Data(bytes: _bb.memory.advanced(by: _bb.writerIndex), return Data(
bytes: _bb.memory.advanced(by: _bb.writerIndex),
count: _bb.capacity &- _bb.writerIndex) count: _bb.capacity &- _bb.writerIndex)
} }
/// Get's the fully sized buffer stored in memory /// Get's the fully sized buffer stored in memory
public var fullSizedByteArray: [UInt8] { public var fullSizedByteArray: [UInt8] {
let ptr = UnsafeBufferPointer(start: _bb.memory.assumingMemoryBound(to: UInt8.self), let ptr = UnsafeBufferPointer(
start: _bb.memory.assumingMemoryBound(to: UInt8.self),
count: _bb.capacity) count: _bb.capacity)
return Array(ptr) return Array(ptr)
} }
@@ -50,7 +68,7 @@ public struct FlatBufferBuilder {
return Array(ptr) return Array(ptr)
} }
/// Returns the buffer /// Returns the buffer
public var buffer: ByteBuffer { return _bb } public var buffer: ByteBuffer { _bb }
/// Returns A sized Buffer from the readable bytes /// Returns A sized Buffer from the readable bytes
public var sizedBuffer: ByteBuffer { public var sizedBuffer: ByteBuffer {
@@ -153,7 +171,10 @@ public struct FlatBufferBuilder {
let _max = Int(_vtableStorage.maxOffset) &+ sizeofVoffset let _max = Int(_vtableStorage.maxOffset) &+ sizeofVoffset
_bb.fill(padding: _max) _bb.fill(padding: _max)
_bb.write(value: VOffset(tableObjectSize), index: _bb.writerIndex &+ sizeofVoffset, direct: true) _bb.write(
value: VOffset(tableObjectSize),
index: _bb.writerIndex &+ sizeofVoffset,
direct: true)
_bb.write(value: VOffset(_max), index: _bb.writerIndex, direct: true) _bb.write(value: VOffset(_max), index: _bb.writerIndex, direct: true)
var itr = 0 var itr = 0
@@ -177,7 +198,7 @@ public struct FlatBufferBuilder {
let position = _bb.capacity &- Int(table) let position = _bb.capacity &- Int(table)
let vt1 = _bb.memory.advanced(by: position) let vt1 = _bb.memory.advanced(by: position)
let len1 = _bb.read(def: Int16.self, position: position) let len1 = _bb.read(def: Int16.self, position: position)
if (len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2))) { continue } if len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2)) { continue }
isAlreadyAdded = Int(table) isAlreadyAdded = Int(table)
break break
@@ -199,13 +220,15 @@ public struct FlatBufferBuilder {
// MARK: - Builds Buffer // MARK: - Builds Buffer
/// asserts to see if the object is not nested /// asserts to see if the object is not nested
@usableFromInline mutating internal func notNested() { @usableFromInline
mutating internal func notNested() {
assert(!isNested, "Object serialization must not be nested") assert(!isNested, "Object serialization must not be nested")
} }
/// Changes the minimuim alignment of the buffer /// Changes the minimuim alignment of the buffer
/// - Parameter size: size of the current alignment /// - Parameter size: size of the current alignment
@usableFromInline mutating internal func minAlignment(size: Int) { @usableFromInline
mutating internal func minAlignment(size: Int) {
if size > _minAlignment { if size > _minAlignment {
_minAlignment = size _minAlignment = size
} }
@@ -215,7 +238,8 @@ public struct FlatBufferBuilder {
/// - Parameters: /// - Parameters:
/// - bufSize: Current size of the buffer + the offset of the object to be written /// - bufSize: Current size of the buffer + the offset of the object to be written
/// - elementSize: Element size /// - elementSize: Element size
@usableFromInline mutating internal func padding(bufSize: UInt32, elementSize: UInt32) -> UInt32 { @usableFromInline
mutating internal func padding(bufSize: UInt32, elementSize: UInt32) -> UInt32 {
((~bufSize) &+ 1) & (elementSize - 1) ((~bufSize) &+ 1) & (elementSize - 1)
} }
@@ -223,22 +247,27 @@ public struct FlatBufferBuilder {
/// - Parameters: /// - Parameters:
/// - len:Length of the object /// - len:Length of the object
/// - alignment: Alignment type /// - alignment: Alignment type
@usableFromInline mutating internal func preAlign(len: Int, alignment: Int) { @usableFromInline
mutating internal func preAlign(len: Int, alignment: Int) {
minAlignment(size: alignment) minAlignment(size: alignment)
_bb.fill(padding: Int(padding(bufSize: _bb.size &+ UOffset(len), elementSize: UOffset(alignment)))) _bb.fill(padding: Int(padding(
bufSize: _bb.size &+ UOffset(len),
elementSize: UOffset(alignment))))
} }
/// Prealigns the buffer before writting a new object into the buffer /// Prealigns the buffer before writting a new object into the buffer
/// - Parameters: /// - Parameters:
/// - len: Length of the object /// - len: Length of the object
/// - type: Type of the object to be written /// - type: Type of the object to be written
@usableFromInline mutating internal func preAlign<T: Scalar>(len: Int, type: T.Type) { @usableFromInline
mutating internal func preAlign<T: Scalar>(len: Int, type: T.Type) {
preAlign(len: len, alignment: MemoryLayout<T>.size) preAlign(len: len, alignment: MemoryLayout<T>.size)
} }
/// Refers to an object that's written in the buffer /// Refers to an object that's written in the buffer
/// - Parameter off: the objects index value /// - Parameter off: the objects index value
@usableFromInline mutating internal func refer(to off: UOffset) -> UOffset { @usableFromInline
mutating internal func refer(to off: UOffset) -> UOffset {
let size = MemoryLayout<UOffset>.size let size = MemoryLayout<UOffset>.size
preAlign(len: size, alignment: size) preAlign(len: size, alignment: size)
return _bb.size &- off &+ UInt32(size) return _bb.size &- off &+ UInt32(size)
@@ -248,7 +277,8 @@ public struct FlatBufferBuilder {
/// - Parameters: /// - Parameters:
/// - offset: The offset of the element witten /// - offset: The offset of the element witten
/// - position: The position of the element /// - position: The position of the element
@usableFromInline mutating internal func track(offset: UOffset, at position: VOffset) { @usableFromInline
mutating internal func track(offset: UOffset, at position: VOffset) {
_vtableStorage.add(loc: FieldLoc(offset: offset, position: position)) _vtableStorage.add(loc: FieldLoc(offset: offset, position: position))
} }
@@ -276,7 +306,7 @@ public struct FlatBufferBuilder {
/// - Parameter elements: elements to be written into the buffer /// - Parameter elements: elements to be written into the buffer
/// - returns: Offset of the vector /// - returns: Offset of the vector
mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset<UOffset> { mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset<UOffset> {
return createVector(elements, size: elements.count) createVector(elements, size: elements.count)
} }
/// Creates a vector of type Scalar in the buffer /// Creates a vector of type Scalar in the buffer
@@ -294,7 +324,7 @@ public struct FlatBufferBuilder {
/// - Parameter elements: elements to be written into the buffer /// - Parameter elements: elements to be written into the buffer
/// - returns: Offset of the vector /// - returns: Offset of the vector
mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset<UOffset> { mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset<UOffset> {
return createVector(elements, size: elements.count) createVector(elements, size: elements.count)
} }
/// Creates a vector of type Enums in the buffer /// Creates a vector of type Enums in the buffer
@@ -347,9 +377,14 @@ public struct FlatBufferBuilder {
/// - structs: An array of UnsafeMutableRawPointer /// - structs: An array of UnsafeMutableRawPointer
/// - type: Type of the struct being written /// - type: Type of the struct being written
/// - returns: Offset of the vector /// - returns: Offset of the vector
@available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") @available(
mutating public func createVector<T: Readable>(structs: [UnsafeMutableRawPointer], *,
type: T.Type) -> Offset<UOffset> { deprecated,
message: "0.9.0 will be removing the following method. Regenerate the code")
mutating public func createVector<T: Readable>(
structs: [UnsafeMutableRawPointer],
type: T.Type) -> Offset<UOffset>
{
startVector(structs.count &* T.size, elementSize: T.alignment) startVector(structs.count &* T.size, elementSize: T.alignment)
for i in structs.reversed() { for i in structs.reversed() {
create(struct: i, type: T.self) create(struct: i, type: T.self)
@@ -370,7 +405,7 @@ public struct FlatBufferBuilder {
/// - Parameter count: number of written elements /// - Parameter count: number of written elements
/// - Returns: Offset of type UOffset /// - Returns: Offset of type UOffset
mutating public func endVectorOfStructs(count: Int) -> Offset<UOffset> { mutating public func endVectorOfStructs(count: Int) -> Offset<UOffset> {
return Offset<UOffset>(offset: endVector(len: count)) Offset<UOffset>(offset: endVector(len: count))
} }
// MARK: - Inserting Structs // MARK: - Inserting Structs
@@ -380,10 +415,15 @@ public struct FlatBufferBuilder {
/// - s: Flatbuffer struct /// - s: Flatbuffer struct
/// - type: Type of the element to be serialized /// - type: Type of the element to be serialized
/// - returns: Offset of the Object /// - returns: Offset of the Object
@available(*, deprecated, message: "0.9.0 will be removing the following method. Regenerate the code") @available(
*,
deprecated,
message: "0.9.0 will be removing the following method. Regenerate the code")
@discardableResult @discardableResult
mutating public func create<T: Readable>(struct s: UnsafeMutableRawPointer, mutating public func create<T: Readable>(
type: T.Type) -> Offset<UOffset> { struct s: UnsafeMutableRawPointer,
type: T.Type) -> Offset<UOffset>
{
let size = T.size let size = T.size
preAlign(len: size, alignment: T.alignment) preAlign(len: size, alignment: T.alignment)
_bb.push(struct: s, size: size) _bb.push(struct: s, size: size)
@@ -404,7 +444,8 @@ public struct FlatBufferBuilder {
/// - v: element of type Scalar /// - v: element of type Scalar
/// - postion: position relative to the `writerIndex` /// - postion: position relative to the `writerIndex`
mutating public func reverseAdd<T: Scalar>(v: T, postion: Int) { mutating public func reverseAdd<T: Scalar>(v: T, postion: Int) {
_bb.reversePush(value: v, _bb.reversePush(
value: v,
position: postion, position: postion,
len: MemoryLayout<T>.size) len: MemoryLayout<T>.size)
} }
@@ -413,7 +454,7 @@ public struct FlatBufferBuilder {
/// - Returns: Offset of type UOffset /// - Returns: Offset of type UOffset
@discardableResult @discardableResult
public func endStruct() -> Offset<UOffset> { public func endStruct() -> Offset<UOffset> {
return Offset(offset: _bb.size) Offset(offset: _bb.size)
} }
/// Adds the offset of a struct into the vTable /// Adds the offset of a struct into the vTable
@@ -483,7 +524,7 @@ public struct FlatBufferBuilder {
/// - def: Default value for that element /// - def: Default value for that element
/// - position: The predefined position of the element /// - position: The predefined position of the element
mutating public func add<T: Scalar>(element: T, def: T, at position: VOffset) { mutating public func add<T: Scalar>(element: T, def: T, at position: VOffset) {
if (element == def && !serializeDefaults) { return } if element == def && !serializeDefaults { return }
track(offset: push(element: element), at: position) track(offset: push(element: element), at: position)
} }
@@ -502,7 +543,8 @@ public struct FlatBufferBuilder {
@discardableResult @discardableResult
mutating public func push<T: Scalar>(element: T) -> UOffset { mutating public func push<T: Scalar>(element: T) -> UOffset {
let size = MemoryLayout<T>.size let size = MemoryLayout<T>.size
preAlign(len: size, preAlign(
len: size,
alignment: size) alignment: size)
_bb.push(value: element, len: size) _bb.push(value: element, len: size)
return _bb.size return _bb.size
@@ -522,7 +564,8 @@ extension FlatBufferBuilder: CustomDebugStringConvertible {
} }
/// VTableStorage is a class to contain the VTable buffer that would be serialized into buffer /// VTableStorage is a class to contain the VTable buffer that would be serialized into buffer
@usableFromInline internal class VTableStorage { @usableFromInline
internal class VTableStorage {
/// Memory check since deallocating each time we want to clear would be expensive /// Memory check since deallocating each time we want to clear would be expensive
/// and memory leaks would happen if we dont deallocate the first allocated memory. /// and memory leaks would happen if we dont deallocate the first allocated memory.
/// memory is promised to be available before adding `FieldLoc` /// memory is promised to be available before adding `FieldLoc`
@@ -540,7 +583,7 @@ extension FlatBufferBuilder: CustomDebugStringConvertible {
/// Last written Index /// Last written Index
var writtenIndex: Int = 0 var writtenIndex: Int = 0
/// the amount of added elements into the buffer /// the amount of added elements into the buffer
var addedElements: Int { return capacity - (numOfFields &* size) } var addedElements: Int { capacity - (numOfFields &* size) }
/// Creates the memory to store the buffer in /// Creates the memory to store the buffer in
init() { init() {
@@ -589,7 +632,7 @@ extension FlatBufferBuilder: CustomDebugStringConvertible {
/// - Parameter index: index of element /// - Parameter index: index of element
/// - Returns: a FieldLoc at index /// - Returns: a FieldLoc at index
func load(at index: Int) -> FieldLoc { func load(at index: Int) -> FieldLoc {
return memory.load(fromByteOffset: index, as: FieldLoc.self) memory.load(fromByteOffset: index, as: FieldLoc.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 Foundation import Foundation
/// FlatbufferObject structures all the Flatbuffers objects /// FlatbufferObject structures all the Flatbuffers objects

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 Foundation import Foundation
public final class FlatBuffersUtils { public final class FlatBuffersUtils {
@@ -5,12 +21,12 @@ 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,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 Foundation import Foundation
extension Int { extension Int {

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.
*/
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
@@ -16,12 +32,14 @@ public final class Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
/// 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

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 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
@@ -39,7 +55,7 @@ extension Mutable where Self == Table {
/// - 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)
} }
} }
@@ -50,7 +66,7 @@ extension Mutable where Self == Struct {
/// - 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
@@ -60,7 +76,7 @@ extension Mutable where Self == Struct {
/// - 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)
} }
} }

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 Foundation import Foundation
public protocol NativeTable {} public protocol NativeTable {}

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 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
@@ -5,7 +21,7 @@ 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,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 Foundation import Foundation
public struct Struct { public struct Struct {
@@ -6,7 +22,7 @@ public struct Struct {
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 {

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 Foundation import Foundation
public struct Table { public struct Table {
@@ -9,20 +25,22 @@ public struct Table {
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.bb = bb
self.postion = position 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.
@@ -41,7 +59,7 @@ public struct Table {
/// - 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.
@@ -68,7 +86,7 @@ public struct Table {
} }
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]? {
@@ -99,11 +117,15 @@ public struct Table {
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 {

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,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 CoreFoundation import CoreFoundation
import FlatBuffers import FlatBuffers
@@ -33,21 +49,24 @@ func createDocument(Benchmarks: [Benchmark]) -> String {
return document return document
} }
@inlinable func create10Strings() { @inlinable
func create10Strings() {
var fb = FlatBufferBuilder(initialSize: 1<<20) var fb = FlatBufferBuilder(initialSize: 1<<20)
for _ in 0..<10_000 { for _ in 0..<10_000 {
_ = fb.create(string: "foobarbaz") _ = fb.create(string: "foobarbaz")
} }
} }
@inlinable func create100Strings(str: String) { @inlinable
func create100Strings(str: String) {
var fb = FlatBufferBuilder(initialSize: 1<<20) var fb = FlatBufferBuilder(initialSize: 1<<20)
for _ in 0..<10_000 { for _ in 0..<10_000 {
_ = fb.create(string: str) _ = fb.create(string: str)
} }
} }
@inlinable func benchmarkFiveHundredAdds() { @inlinable
func benchmarkFiveHundredAdds() {
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
for _ in 0..<500_000 { for _ in 0..<500_000 {
let off = fb.create(string: "T") let off = fb.create(string: "T")
@@ -60,7 +79,8 @@ func createDocument(Benchmarks: [Benchmark]) -> String {
} }
} }
@inlinable func benchmarkThreeMillionStructs() { @inlinable
func benchmarkThreeMillionStructs() {
let structCount = 3_000_000 let structCount = 3_000_000
let rawSize = ((16 * 5) * structCount) / 1024 let rawSize = ((16 * 5) * structCount) / 1024
@@ -90,7 +110,7 @@ func createDocument(Benchmarks: [Benchmark]) -> String {
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) {

View File

@@ -1,5 +1,19 @@
// 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
@@ -11,7 +25,7 @@ let package = Package(
], ],
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.
@@ -20,10 +34,9 @@ let package = Package(
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(
@@ -32,8 +45,7 @@ let package = Package(
"GRPC", "GRPC",
"Model", "Model",
], ],
path: "Sources/client" path: "Sources/client"),
),
// Server for the Greeter example // Server for the Greeter example
.target( .target(
@@ -42,7 +54,5 @@ let package = Package(
"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
@@ -71,5 +75,3 @@ public extension GreeterProvider {
} }
} }

View File

@@ -1,5 +1,6 @@
// 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

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,11 +14,11 @@
* 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 {
@@ -46,7 +46,10 @@ func greet(name: String, client greeter: GreeterServiceClient) {
} }
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,
offsetOfName: surname,
numGreetings: 2)
builder.finish(offset: manyRoot) builder.finish(offset: manyRoot)
let call = greeter.SayManyHellos(Message(builder: &builder)) { message in let call = greeter.SayManyHellos(Message(builder: &builder)) { message in

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,11 +14,11 @@
* 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 {
@@ -37,8 +37,8 @@ class Greeter: GreeterProvider {
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()
@@ -50,8 +50,8 @@ class Greeter: GreeterProvider {
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])
@@ -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,5 +1,19 @@
// 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
@@ -11,12 +25,11 @@ let package = Package(
], ],
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

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
@testable import FlatBuffers @testable import FlatBuffers
@@ -28,9 +44,9 @@ struct Vec: Readable {
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

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
@testable import FlatBuffers @testable import FlatBuffers
@@ -68,7 +84,8 @@ final class FlatBuffersTests: XCTestCase {
func testWriteOptionalValues() { func testWriteOptionalValues() {
var b = FlatBufferBuilder() var b = FlatBufferBuilder()
let root = optional_scalars_ScalarStuff.createScalarStuff(&b, let root = optional_scalars_ScalarStuff.createScalarStuff(
&b,
justI8: 80, justI8: 80,
maybeI8: nil, maybeI8: nil,
justU8: 100, justU8: 100,
@@ -100,18 +117,31 @@ class Country {
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
static func createCountry(
builder: inout FlatBufferBuilder,
offset: Offset<String>,
log: Int32,
lan: Int32) -> Offset<Country>
{
let _start = builder.startTable(with: 3) let _start = builder.startTable(with: 3)
Country.add(builder: &builder, lng: log) Country.add(builder: &builder, lng: log)
Country.add(builder: &builder, lan: lan) Country.add(builder: &builder, lan: lan)
@@ -119,23 +149,28 @@ class Country {
return Country.end(builder: &builder, startOffset: _start) 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
static func add(builder: inout FlatBufferBuilder, name: String) {
add(builder: &builder, name: builder.create(string: name)) add(builder: &builder, name: builder.create(string: name))
} }
@inlinable static func add(builder: inout FlatBufferBuilder, name: Offset<String>) { @inlinable
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)
} }
@inlinable static func add(builder: inout FlatBufferBuilder, lan: Int32) { @inlinable
static func add(builder: inout FlatBufferBuilder, lan: Int32) {
builder.add(element: lan, def: 0, at: Country.offsets.lan) builder.add(element: lan, def: 0, at: Country.offsets.lan)
} }
@inlinable static func add(builder: inout FlatBufferBuilder, lng: Int32) { @inlinable
static func add(builder: inout FlatBufferBuilder, lng: Int32) {
builder.add(element: lng, def: 0, at: Country.offsets.lng) builder.add(element: lng, def: 0, at: Country.offsets.lng)
} }
} }

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
@testable import FlatBuffers @testable import FlatBuffers
@@ -11,7 +27,8 @@ final class FlatBuffersUnionTests: XCTestCase {
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(
builder: &b,
offset: weapons, offset: weapons,
equipment: .Weapon, equipment: .Weapon,
equippedOffset: weapon.o) equippedOffset: weapon.o)
@@ -42,7 +59,8 @@ final class FlatBuffersUnionTests: XCTestCase {
createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0) createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0)
createVecWrite(builder: &builder, x: 4.0, y: 5.0, z: 6.0) createVecWrite(builder: &builder, x: 4.0, y: 5.0, z: 6.0)
let path = builder.endVectorOfStructs(count: 2) let path = builder.endVectorOfStructs(count: 2)
let orc = FinalMonster.createMonster(builder: &builder, let orc = FinalMonster.createMonster(
builder: &builder,
position: createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0), position: createVecWrite(builder: &builder, x: 1.0, y: 2.0, z: 3.0),
hp: 300, hp: 300,
name: name, name: name,
@@ -85,7 +103,7 @@ final class FlatBuffersUnionTests: XCTestCase {
let characters = [ let characters = [
BookReader.createBookReader(builder: &fb, booksRead: 7), BookReader.createBookReader(builder: &fb, booksRead: 7),
attack, attack,
BookReader.createBookReader(builder: &fb, booksRead: 2) BookReader.createBookReader(builder: &fb, booksRead: 2),
] ]
let types = fb.createVector(characterType) let types = fb.createVector(characterType)
let characterVector = fb.createVector(ofOffsets: characters) let characterVector = fb.createVector(ofOffsets: characters)
@@ -123,8 +141,8 @@ 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
} }
@@ -132,15 +150,21 @@ public enum ColorsNameSpace {
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(
of: Int32.self,
offset: _accessor.vector(at: o) + index * 4)) }
static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } 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 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 } static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
} }
} }
@@ -152,7 +176,9 @@ enum Color3: Int8 { case red = 0, green, blue }
struct FinalMonster { struct FinalMonster {
@inlinable static func createMonster(builder: inout FlatBufferBuilder, @inlinable
static func createMonster(
builder: inout FlatBufferBuilder,
position: Offset<UOffset>, position: Offset<UOffset>,
hp: Int16, hp: Int16,
name: Offset<String>, name: Offset<String>,
@@ -161,7 +187,8 @@ struct FinalMonster {
weapons: Offset<UOffset>, weapons: Offset<UOffset>,
equipment: Equipment = .none, equipment: Equipment = .none,
equippedOffset: Offset<Weapon>, equippedOffset: Offset<Weapon>,
path: Offset<UOffset>) -> Offset<LocalMonster> { path: Offset<UOffset>) -> Offset<LocalMonster>
{
let start = builder.startTable(with: 11) let start = builder.startTable(with: 11)
builder.add(structOffset: 4) builder.add(structOffset: 4)
builder.add(element: hp, def: 100, at: 8) builder.add(element: hp, def: 100, at: 8)
@@ -183,20 +210,25 @@ struct LocalMonster {
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
static func createMonster(
builder: inout FlatBufferBuilder,
offset: Offset<UOffset>, offset: Offset<UOffset>,
equipment: Equipment = .none, equipment: Equipment = .none,
equippedOffset: UOffset) -> Offset<LocalMonster> { equippedOffset: UOffset) -> Offset<LocalMonster>
{
let start = builder.startTable(with: 3) let start = builder.startTable(with: 3)
builder.add(element: equippedOffset, def: 0, at: 8) builder.add(element: equippedOffset, def: 0, at: 8)
builder.add(offset: offset, at: 4) builder.add(offset: offset, at: 4)
@@ -216,27 +248,35 @@ struct Weapon: FlatBufferObject {
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
static func createWeapon(
builder: inout FlatBufferBuilder,
offset: Offset<String>,
dmg: Int16) -> Offset<Weapon>
{
let _start = builder.startTable(with: 2) let _start = builder.startTable(with: 2)
Weapon.add(builder: &builder, name: offset) Weapon.add(builder: &builder, name: offset)
Weapon.add(builder: &builder, dmg: dmg) Weapon.add(builder: &builder, dmg: dmg)
return Weapon.end(builder: &builder, startOffset: _start) 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
static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
builder.add(offset: name, at: Weapon.offsets.name) builder.add(offset: name, at: Weapon.offsets.name)
} }
@inlinable static func add(builder: inout FlatBufferBuilder, dmg: Int16) { @inlinable
static func add(builder: inout FlatBufferBuilder, dmg: Int16) {
builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg) builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg)
} }
} }

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
@testable import FlatBuffers @testable import FlatBuffers
@@ -83,29 +99,30 @@ struct Numbers {
__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> {

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
@testable import FlatBuffers @testable import FlatBuffers
@@ -35,11 +51,21 @@ class CountryDouble {
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(
builder: inout FlatBufferBuilder,
offset: Offset<String>,
log: Double,
lan: Double) -> Offset<Country>
{
let _start = builder.startTable(with: 3) let _start = builder.startTable(with: 3)
CountryDouble.add(builder: &builder, lng: log) CountryDouble.add(builder: &builder, lng: log)
CountryDouble.add(builder: &builder, lan: lan) CountryDouble.add(builder: &builder, lan: lan)
@@ -48,7 +74,7 @@ class CountryDouble {
} }
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) {

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 !canImport(ObjectiveC) #if !canImport(ObjectiveC)
import XCTest import XCTest
@@ -19,11 +35,17 @@ extension FlatBuffersMonsterWriterTests {
("testCreateMonster", testCreateMonster), ("testCreateMonster", testCreateMonster),
("testCreateMonsterPrefixed", testCreateMonsterPrefixed), ("testCreateMonsterPrefixed", testCreateMonsterPrefixed),
("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer), ("testCreateMonsterResizedBuffer", testCreateMonsterResizedBuffer),
("testCreateMonsterUsingCreateMonsterMethodWithNilPos", testCreateMonsterUsingCreateMonsterMethodWithNilPos), (
("testCreateMonsterUsingCreateMonsterMethodWithPosX", testCreateMonsterUsingCreateMonsterMethodWithPosX), "testCreateMonsterUsingCreateMonsterMethodWithNilPos",
testCreateMonsterUsingCreateMonsterMethodWithNilPos),
(
"testCreateMonsterUsingCreateMonsterMethodWithPosX",
testCreateMonsterUsingCreateMonsterMethodWithPosX),
("testData", testData), ("testData", testData),
("testReadFromOtherLanguages", testReadFromOtherLanguages), ("testReadFromOtherLanguages", testReadFromOtherLanguages),
("testReadMonsterFromUnsafePointerWithoutCopying", testReadMonsterFromUnsafePointerWithoutCopying), (
"testReadMonsterFromUnsafePointerWithoutCopying",
testReadMonsterFromUnsafePointerWithoutCopying),
] ]
} }
@@ -81,7 +103,7 @@ extension FlatBuffersVectors {
} }
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),

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
@@ -91,5 +95,3 @@ public extension MyGame_Example_MonsterStorageProvider {
} }
} }

View File

@@ -1,5 +1,6 @@
// 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

View File

@@ -1,5 +1,6 @@
// 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

View File

@@ -1,5 +1,6 @@
// 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

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