Skip to content

Commit 5fe90a9

Browse files
authored
[Swift] Implements FlatbuffersVector which confirms to RandomAccessCollection (#8752)
* Implements FlatbuffersVector in swift Implements FlatbuffersVector which confirms to RandomAccessCollection, this would give us semi-native sugary syntax to all the arrays in swift port. This work will also be the foundation of using arrays in swift * Fix failing tests for Swift
1 parent 78a3d59 commit 5fe90a9

File tree

63 files changed

+1554
-1650
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+1554
-1650
lines changed

Package.swift

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,24 +57,24 @@ let package = Package(
5757
extension Array where Element == Package.Dependency {
5858
static var dependencies: [Package.Dependency] {
5959
#if os(Windows)
60-
[]
60+
[]
6161
#else
62-
// Test only Dependency
63-
[.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")]
62+
// Test only Dependency
63+
[.package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1")]
6464
#endif
6565
}
6666
}
6767

6868
extension Array where Element == PackageDescription.Target.Dependency {
6969
static var dependencies: [PackageDescription.Target.Dependency] {
7070
#if os(Windows)
71-
["FlatBuffers"]
71+
["FlatBuffers"]
7272
#else
73-
// Test only Dependency
74-
[
75-
.product(name: "GRPC", package: "grpc-swift"),
76-
"FlatBuffers",
77-
]
73+
// Test only Dependency
74+
[
75+
.product(name: "GRPC", package: "grpc-swift"),
76+
"FlatBuffers",
77+
]
7878
#endif
7979
}
8080
}

benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,8 @@ let benchmarks = {
8888

8989
Benchmark(
9090
"Allocating ByteBuffer 1GB",
91-
configuration: singleConfiguration
92-
) { benchmark in
91+
configuration: singleConfiguration)
92+
{ benchmark in
9393
let memory = UnsafeMutableRawPointer.allocate(
9494
byteCount: 1_024_000_000,
9595
alignment: 1)
@@ -165,8 +165,8 @@ let benchmarks = {
165165

166166
Benchmark(
167167
"FlatBufferBuilder Add",
168-
configuration: kiloConfiguration
169-
) { benchmark in
168+
configuration: kiloConfiguration)
169+
{ benchmark in
170170
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
171171
benchmark.startMeasurement()
172172
for _ in benchmark.scaledIterations {
@@ -182,8 +182,8 @@ let benchmarks = {
182182

183183
Benchmark(
184184
"FlatBufferBuilder Start table",
185-
configuration: kiloConfiguration
186-
) { benchmark in
185+
configuration: kiloConfiguration)
186+
{ benchmark in
187187
var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
188188
benchmark.startMeasurement()
189189
for _ in benchmark.scaledIterations {

benchmarks/swift/Package.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import PackageDescription
2020
let package = Package(
2121
name: "benchmarks",
2222
platforms: [
23-
.macOS(.v13)
23+
.macOS(.v13),
2424
],
2525
dependencies: [
2626
.package(path: "../.."),
@@ -37,6 +37,6 @@ let package = Package(
3737
],
3838
path: "Benchmarks/FlatbuffersBenchmarks",
3939
plugins: [
40-
.plugin(name: "BenchmarkPlugin", package: "package-benchmark")
41-
])
40+
.plugin(name: "BenchmarkPlugin", package: "package-benchmark"),
41+
]),
4242
])

grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Common
88

99
import FlatBuffers
1010

11-
public struct models_HelloReply: FlatBufferObject, Verifiable {
11+
public struct models_HelloReply: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable {
1212

1313
static func validateVersion() { FlatBuffersVersion_25_9_23() }
1414
public var __buffer: ByteBuffer! { return _accessor.bb }
@@ -55,7 +55,7 @@ extension models_HelloReply: Encodable {
5555
}
5656
}
5757

58-
public struct models_HelloRequest: FlatBufferObject, Verifiable {
58+
public struct models_HelloRequest: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable {
5959

6060
static func validateVersion() { FlatBuffersVersion_25_9_23() }
6161
public var __buffer: ByteBuffer! { return _accessor.bb }

grpc/examples/swift/Greeter/Sources/client/main.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func greet(name: String, client greeter: models_GreeterServiceClient) {
3939
// Make the RPC call to the server.
4040
let sayHello =
4141
greeter
42-
.SayHello(Message<models_HelloRequest>(builder: &builder))
42+
.SayHello(Message<models_HelloRequest>(builder: &builder))
4343

4444
// wait() on the response to stop the program from exiting before the response is received.
4545
do {

grpc/examples/swift/Greeter/Sources/server/main.swift

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ class Greeter: models_GreeterProvider {
3232

3333
func SayHello(
3434
request: Message<models_HelloRequest>,
35-
context: StatusOnlyCallContext
36-
)
35+
context: StatusOnlyCallContext)
3736
-> EventLoopFuture<Message<models_HelloReply>>
3837
{
3938
let recipient = request.object.name ?? "Stranger"
@@ -48,15 +47,14 @@ class Greeter: models_GreeterProvider {
4847

4948
func SayManyHellos(
5049
request: Message<models_HelloRequest>,
51-
context: StreamingResponseCallContext<Message<models_HelloReply>>
52-
)
50+
context: StreamingResponseCallContext<Message<models_HelloReply>>)
5351
-> EventLoopFuture<GRPCStatus>
5452
{
5553
for name in greetings {
5654
var builder = FlatBufferBuilder()
5755
let off =
5856
builder
59-
.create(string: "\(name) \(request.object.name ?? "Unknown")")
57+
.create(string: "\(name) \(request.object.name ?? "Unknown")")
6058
let root = models_HelloReply.createHelloReply(
6159
&builder,
6260
messageOffset: off)

samples/monster_generated.swift

Lines changed: 22 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Common
88

99
import FlatBuffers
1010

11-
public enum MyGame_Sample_Color: Int8, Enum, Verifiable {
11+
public enum MyGame_Sample_Color: Int8, FlatbuffersVectorInitializable, Enum, Verifiable {
1212
public typealias T = Int8
1313
public static var byteSize: Int { return MemoryLayout<Int8>.size }
1414
public var value: Int8 { return self.rawValue }
@@ -31,7 +31,7 @@ extension MyGame_Sample_Color: Encodable {
3131
}
3232
}
3333

34-
public enum MyGame_Sample_Equipment: UInt8, UnionEnum {
34+
public enum MyGame_Sample_Equipment: UInt8, FlatbuffersVectorInitializable, UnionEnum {
3535
public typealias T = UInt8
3636

3737
public init?(value: T) {
@@ -73,7 +73,7 @@ public struct MyGame_Sample_EquipmentUnion {
7373
}
7474
}
7575
}
76-
public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
76+
public struct MyGame_Sample_Vec3: NativeStruct, FlatbuffersVectorInitializable, Verifiable, FlatbuffersInitializable, NativeObject {
7777

7878
static func validateVersion() { FlatBuffersVersion_25_9_23() }
7979

@@ -136,7 +136,7 @@ extension MyGame_Sample_Vec3: Encodable {
136136
}
137137
}
138138

139-
public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
139+
public struct MyGame_Sample_Vec3_Mutable: FlatBufferStruct, FlatbuffersVectorInitializable {
140140

141141
static func validateVersion() { FlatBuffersVersion_25_9_23() }
142142
public var __buffer: ByteBuffer! { return _accessor.bb }
@@ -165,7 +165,7 @@ public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
165165
}
166166
}
167167

168-
public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker {
168+
public struct MyGame_Sample_Monster: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker {
169169

170170
static func validateVersion() { FlatBuffersVersion_25_9_23() }
171171
public var __buffer: ByteBuffer! { return _accessor.bb }
@@ -197,24 +197,17 @@ public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable, ObjectAPIPack
197197
@discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.hp.v); return _accessor.mutate(hp, index: o) }
198198
public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
199199
public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
200-
public var hasInventory: Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? false : true }
201-
public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) }
202-
public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
203-
public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] }
200+
public var inventory: FlatbufferVector<UInt8> { return _accessor.vector(at: VTOFFSET.inventory.v, byteSize: 1) }
204201
public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) }
205-
public func withUnsafePointerToInventory<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.inventory.v, body: body) }
202+
public func withUnsafePointerToInventory<T>(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.inventory.v, body: body) }
206203
public var color: MyGame_Sample_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Sample_Color(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .blue }
207204
@discardableResult public func mutate(color: MyGame_Sample_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) }
208-
public var hasWeapons: Bool { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? false : true }
209-
public var weaponsCount: Int32 { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? 0 : _accessor.vector(count: o) }
210-
public func weapons(at index: Int32) -> MyGame_Sample_Weapon? { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? nil : MyGame_Sample_Weapon(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
205+
public var weapons: FlatbufferVector<MyGame_Sample_Weapon> { return _accessor.vector(at: VTOFFSET.weapons.v, byteSize: 4) }
211206
public var equippedType: MyGame_Sample_Equipment { let o = _accessor.offset(VTOFFSET.equippedType.v); return o == 0 ? .none_ : MyGame_Sample_Equipment(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ }
212207
public func equipped<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.equipped.v); return o == 0 ? nil : _accessor.union(o) }
213-
public var hasPath: Bool { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? false : true }
214-
public var pathCount: Int32 { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? 0 : _accessor.vector(count: o) }
215-
public func path(at index: Int32) -> MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Sample_Vec3.self, offset: _accessor.vector(at: o) + index * 12) }
216-
public func mutablePath(at index: Int32) -> MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 12) }
217-
public func withUnsafePointerToPath<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.path.v, body: body) }
208+
public var path: FlatbufferVector<MyGame_Sample_Vec3> { return _accessor.vector(at: VTOFFSET.path.v, byteSize: 12) }
209+
public var mutablePath: FlatbufferVector<MyGame_Sample_Vec3_Mutable> { return _accessor.vector(at: VTOFFSET.path.v, byteSize: 12) }
210+
public func withUnsafePointerToPath<T>(_ body: (UnsafeRawBufferPointer, Int) throws -> T) rethrows -> T? { return try _accessor.withUnsafePointerToSlice(at: VTOFFSET.path.v, body: body) }
218211
public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 11) }
219212
public static func add(pos: MyGame_Sample_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) }
220213
public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) }
@@ -282,9 +275,8 @@ public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable, ObjectAPIPack
282275
let __weapons = builder.createVector(ofOffsets: __weapons__)
283276
let __equipped = obj.equipped?.pack(builder: &builder) ?? Offset()
284277
MyGame_Sample_Monster.startVectorOfPath(obj.path.count, in: &builder)
285-
for i in obj.path {
286-
guard let _o = i else { continue }
287-
builder.create(struct: _o)
278+
for val in obj.path {
279+
builder.create(struct: val)
288280
}
289281
let __path = builder.endVector(len: obj.path.count)
290282
let __root = MyGame_Sample_Monster.startMonster(&builder)
@@ -350,19 +342,11 @@ extension MyGame_Sample_Monster: Encodable {
350342
try container.encodeIfPresent(hp, forKey: .hp)
351343
}
352344
try container.encodeIfPresent(name, forKey: .name)
353-
if inventoryCount > 0 {
354-
try container.encodeIfPresent(inventory, forKey: .inventory)
355-
}
345+
try container.encodeIfPresent(inventory, forKey: .inventory)
356346
if color != .blue {
357347
try container.encodeIfPresent(color, forKey: .color)
358348
}
359-
if weaponsCount > 0 {
360-
var contentEncoder = container.nestedUnkeyedContainer(forKey: .weapons)
361-
for index in 0..<weaponsCount {
362-
guard let type = weapons(at: index) else { continue }
363-
try contentEncoder.encode(type)
364-
}
365-
}
349+
try container.encodeIfPresent(weapons, forKey: .weapons)
366350
if equippedType != .none_ {
367351
try container.encodeIfPresent(equippedType, forKey: .equippedType)
368352
}
@@ -372,13 +356,7 @@ extension MyGame_Sample_Monster: Encodable {
372356
try container.encodeIfPresent(_v, forKey: .equipped)
373357
default: break;
374358
}
375-
if pathCount > 0 {
376-
var contentEncoder = container.nestedUnkeyedContainer(forKey: .path)
377-
for index in 0..<pathCount {
378-
guard let type = path(at: index) else { continue }
379-
try contentEncoder.encode(type)
380-
}
381-
}
359+
try container.encodeIfPresent(path, forKey: .path)
382360
}
383361
}
384362

@@ -392,22 +370,19 @@ public class MyGame_Sample_MonsterT: NativeObject {
392370
public var color: MyGame_Sample_Color
393371
public var weapons: [MyGame_Sample_WeaponT?]
394372
public var equipped: MyGame_Sample_EquipmentUnion?
395-
public var path: [MyGame_Sample_Vec3?]
373+
public var path: [MyGame_Sample_Vec3]
396374

397375
public init(_ _t: inout MyGame_Sample_Monster) {
398376
pos = _t.pos
399377
mana = _t.mana
400378
hp = _t.hp
401379
name = _t.name
402380
inventory = []
403-
for index in 0..<_t.inventoryCount {
404-
inventory.append(_t.inventory(at: index))
405-
}
381+
inventory.append(contentsOf: _t.inventory)
406382
color = _t.color
407383
weapons = []
408-
for index in 0..<_t.weaponsCount {
409-
var __v_ = _t.weapons(at: index)
410-
weapons.append(__v_?.unpack())
384+
for var val in _t.weapons{
385+
weapons.append(val.unpack())
411386
}
412387
switch _t.equippedType {
413388
case .weapon:
@@ -416,9 +391,7 @@ public class MyGame_Sample_MonsterT: NativeObject {
416391
default: break
417392
}
418393
path = []
419-
for index in 0..<_t.pathCount {
420-
path.append(_t.path(at: index))
421-
}
394+
path.append(contentsOf: _t.path)
422395
}
423396

424397
public init() {
@@ -434,7 +407,7 @@ public class MyGame_Sample_MonsterT: NativeObject {
434407
public func serialize() -> ByteBuffer { return serialize(type: MyGame_Sample_Monster.self) }
435408

436409
}
437-
public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable, ObjectAPIPacker {
410+
public struct MyGame_Sample_Weapon: FlatBufferTable, FlatbuffersVectorInitializable, Verifiable, ObjectAPIPacker {
438411

439412
static func validateVersion() { FlatBuffersVersion_25_9_23() }
440413
public var __buffer: ByteBuffer! { return _accessor.bb }

0 commit comments

Comments
 (0)