Table

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// `Table` is a Flatbuffers object that can read,
/// mutate scalar fields within a valid flatbuffers buffer
public struct Table {
  /// Hosting Bytebuffer
  public private(set) var bb: ByteBuffer
  /// Current position of the table within the buffer
  public private(set) var postion: Int32
  /// Initializer for the table interface to allow generated code to read
  /// data from memory
  /// - Parameters:
  ///   - bb: ByteBuffer that stores data
  ///   - position: Current table position
  /// - Note: This will `CRASH` if read on a big endian machine
  public init(bb: ByteBuffer, position: Int32 = 0) {
    guard isLitteEndian else {
      fatalError(
        "Reading/Writing a buffer in big endian machine is not supported on swift")
    }
    self.bb = bb
    postion = position
  }
  /// Gets the offset of the current field within the buffer by reading
  /// the vtable
  /// - Parameter o: current offset
  /// - Returns: offset of field within buffer
  public func offset(_ o: Int32) -> Int32 {
    let vtable = 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
  }
  /// Gets the indirect offset of the current stored object
  /// (applicable only for object arrays)
  /// - Parameter o: current offset
  /// - Returns: offset of field within buffer
  public func indirect(_ o: Int32) -> Int32 {
    o + bb.read(def: Int32.self, position: Int(o))
  }
  /// String reads from the buffer with respect to position of the current table.
  /// - Parameter offset: Offset of the string
  public func string(at offset: Int32) -> String? {
    directString(at: offset + postion)
  }
  /// Direct string reads from the buffer disregarding the position of the table.
  /// It would be preferable to use string unless the current position of the table
  /// is not needed
  /// - Parameter offset: Offset of the string
  public func directString(at offset: Int32) -> String? {
    var offset = offset
    offset += bb.read(def: Int32.self, position: Int(offset))
    let count = bb.read(def: Int32.self, position: Int(offset))
    let position = Int(offset) + MemoryLayout<Int32>.size
    return bb.readString(at: position, count: Int(count))
  }
  /// Reads from the buffer with respect to the position in the table.
  /// - Parameters:
  ///   - type: Type of Element that needs to be read from the buffer
  ///   - o: Offset of the Element
  public func readBuffer<T>(of type: T.Type, at o: Int32) -> T {
    directRead(of: T.self, offset: o + postion)
  }
  /// Reads from the buffer disregarding the position of the table.
  /// It would be used when reading from an
  ///   ```
  ///   let offset = __t.offset(10)
  ///   //Only used when the we already know what is the
  ///   // position in the table since __t.vector(at:)
  ///   // returns the index with respect to the position
  ///   __t.directRead(of: Byte.self,
  ///                  offset: __t.vector(at: offset) + index * 1)
  ///   ```
  /// - Parameters:
  ///   - type: Type of Element that needs to be read from the buffer
  ///   - o: Offset of the Element
  public func directRead<T>(of type: T.Type, offset o: Int32) -> T {
    let r = bb.read(def: T.self, position: Int(o))
    return r
  }
  /// Returns that current `Union` object at a specific offset
  /// by adding offset to the current position of table
  /// - Parameter o: offset
  /// - Returns: A flatbuffers object
  public func union<T: FlatbuffersInitializable>(_ o: Int32) -> T {
    let o = o + postion
    return directUnion(o)
  }
  /// Returns a direct `Union` object at a specific offset
  /// - Parameter o: offset
  /// - Returns: A flatbuffers object
  public func directUnion<T: FlatbuffersInitializable>(_ o: Int32) -> T {
    T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o)))
  }
  /// Returns a vector of type T at a specific offset
  /// This should only be used by `Scalars`
  /// - Parameter off: Readable offset
  /// - Returns: Returns a vector of type [T]
  public func getVector<T>(at off: Int32) -> [T]? {
    let o = offset(off)
    guard o != 0 else { return nil }
    return bb.readSlice(index: Int(vector(at: o)), count: Int(vector(count: o)))
  }
  /// Vector count gets the count of Elements within the array
  /// - Parameter o: start offset of the vector
  /// - returns: Count of elements
  public func vector(count o: Int32) -> Int32 {
    var o = o
    o += postion
    o += bb.read(def: Int32.self, position: Int(o))
    return bb.read(def: Int32.self, position: Int(o))
  }
  /// Vector start index in the buffer
  /// - Parameter o:start offset of the vector
  /// - returns: the start index of the vector
  public func vector(at o: Int32) -> Int32 {
    var o = o
    o += postion
    return o + bb.read(def: Int32.self, position: Int(o)) + 4
  }
  /// Reading an indirect offset of a table.
  /// - Parameters:
  ///   - o: position within the buffer
  ///   - fbb: ByteBuffer
  /// - Returns: table offset
  static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 {
    o + fbb.read(def: Int32.self, position: Int(o))
  }
  /// Gets a vtable value according to an table Offset and a field offset
  /// - Parameters:
  ///   - o: offset relative to entire buffer
  ///   - vOffset: Field offset within a vtable
  ///   - fbb: ByteBuffer
  /// - Returns: an position of a field
  static public func offset(
    _ o: Int32,
    vOffset: Int32,
    fbb: ByteBuffer) -> Int32
  {
    let vTable = Int32(fbb.capacity) - o
    return vTable + Int32(fbb.read(
      def: Int16.self,
      position: Int(vTable + vOffset - fbb.read(
        def: Int32.self,
        position: Int(vTable)))))
  }
  /// Compares two objects at offset A and offset B within a ByteBuffer
  /// - Parameters:
  ///   - off1: first offset to compare
  ///   - off2: second offset to compare
  ///   - fbb: Bytebuffer
  /// - Returns: returns the difference between
  static public func compare(
    _ off1: Int32,
    _ off2: Int32,
    fbb: ByteBuffer) -> Int32
  {
    let memorySize = Int32(MemoryLayout<Int32>.size)
    let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
    let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2))
    let len1 = fbb.read(def: Int32.self, position: Int(_off1))
    let len2 = fbb.read(def: Int32.self, position: Int(_off2))
    let startPos1 = _off1 + memorySize
    let startPos2 = _off2 + memorySize
    let minValue = min(len1, len2)
    for i in 0...minValue {
      let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1))
      let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2))
      if b1 != b2 {
        return Int32(b2 - b1)
      }
    }
    return len1 - len2
  }
  /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer
  /// - Parameters:
  ///   - off1: Offset to compare to
  ///   - key: bytes array to compare to
  ///   - fbb: Bytebuffer
  /// - Returns: returns the difference between
  static public func compare(
    _ off1: Int32,
    _ key: [Byte],
    fbb: ByteBuffer) -> Int32
  {
    let memorySize = Int32(MemoryLayout<Int32>.size)
    let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1))
    let len1 = fbb.read(def: Int32.self, position: Int(_off1))
    let len2 = Int32(key.count)
    let startPos1 = _off1 + memorySize
    let minValue = min(len1, len2)
    for i in 0..<minValue {
      let b = fbb.read(def: Int8.self, position: Int(i + startPos1))
      let byte = key[Int(i)]
      if b != byte {
        return Int32(b - Int8(byte))
      }
    }
    return len1 - len2
  }
}


Constants

/*
 */
#if !os(WASI)
  #if os(Linux)
  import CoreFoundation
  #else
  import Foundation
  #endif
#else
import SwiftOverlayShims
#endif
/// A boolean to see if the system is littleEndian
let isLitteEndian: Bool = {
  let number: UInt32 = 0x12345678
  return number == number.littleEndian
}()
/// Constant for the file id length
let FileIdLength = 4
/// Type aliases
public typealias Byte = UInt8
public typealias UOffset = UInt32
public typealias SOffset = Int32
public typealias VOffset = UInt16
/// Maximum size for a buffer
public let FlatBufferMaxSize = UInt32
  .max << ((MemoryLayout<SOffset>.size * 8 - 1) - 1)
/// Protocol that All Scalars should conform to
///
/// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer.
public protocol Scalar: Equatable {
  associatedtype NumericValue
  var convertedEndian: NumericValue { get }
}
extension Scalar where Self: Verifiable {}
extension Scalar where Self: FixedWidthInteger {
  /// Converts the value from BigEndian to LittleEndian
  ///
  /// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet.
  public var convertedEndian: NumericValue {
    self as! Self.NumericValue
  }
}
extension Double: Scalar, Verifiable {
  public typealias NumericValue = UInt64
  public var convertedEndian: UInt64 {
    bitPattern.littleEndian
  }
}
extension Float32: Scalar, Verifiable {
  public typealias NumericValue = UInt32
  public var convertedEndian: UInt32 {
    bitPattern.littleEndian
  }
}
extension Bool: Scalar, Verifiable {
  public var convertedEndian: UInt8 {
    self == true ? 1 : 0
  }
  public typealias NumericValue = UInt8
}
extension Int: Scalar, Verifiable {
  public typealias NumericValue = Int
}
extension Int8: Scalar, Verifiable {
  public typealias NumericValue = Int8
}
extension Int16: Scalar, Verifiable {
  public typealias NumericValue = Int16
}
extension Int32: Scalar, Verifiable {
  public typealias NumericValue = Int32
}
extension Int64: Scalar, Verifiable {
  public typealias NumericValue = Int64
}
extension UInt8: Scalar, Verifiable {
  public typealias NumericValue = UInt8
}
extension UInt16: Scalar, Verifiable {
  public typealias NumericValue = UInt16
}
extension UInt32: Scalar, Verifiable {
  public typealias NumericValue = UInt32
}
extension UInt64: Scalar, Verifiable {
  public typealias NumericValue = UInt64
}
public func FlatBuffersVersion_2_0_0() {}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")

  // start creating the weapon by calling startWeapon
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: 3, &builder)
  // end the object by passing the start point for the weapon 1
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)

  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: 5, &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)

  // Create a FlatBuffer `vector` that contains offsets to the sword and axe
  // we created above.
  let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])

  // Name of the Monster.
  let name = builder.create(string: "Orc")

  let pathOffset = fbb.createVector(ofStructs: [
    Vec3(x: 0, y: 0),
    Vec3(x: 5, y: 5),
  ])

  // startVector(len, elementSize: MemoryLayout<Offset>.size)
  // for o in offsets.reversed() {
  //   push(element: o)
  // }
  // endVector(len: len)
}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")

  // start creating the weapon by calling startWeapon
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: 3, &builder)
  // end the object by passing the start point for the weapon 1
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)

  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: 5, &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)
}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")
}


import FlatBuffers
import Foundation


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")

  // start creating the weapon by calling startWeapon
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: 3, &builder)
  // end the object by passing the start point for the weapon 1
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)

  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: 5, &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)

  // Create a FlatBuffer `vector` that contains offsets to the sword and axe
  // we created above.
  let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])

  // Name of the Monster.
  let name = builder.create(string: "Orc")

  let pathOffset = fbb.createVector(ofStructs: [
    Vec3(x: 0, y: 0),
    Vec3(x: 5, y: 5),
  ])

  // startVector(len, elementSize: MemoryLayout<Offset>.size)
  // for o in offsets.reversed() {
  //   push(element: o)
  // }
  // endVector(len: len)

  let orc = Monster.createMonster(
    &builder,
    pos: Vec3(x: 1, y: 2),
    hp: 300,
    nameOffset: name,
    color: .red,
    weaponsVectorOffset: weaponsOffset,
    equippedType: .weapon,
    equippedOffset: axe,
    pathOffset: pathOffset)

  // let start = Monster.startMonster(&builder)
  // Monster.add(pos: Vec3(x: 1, y: 2), &builder)
  // Monster.add(hp: 300, &builder)
  // Monster.add(name: name, &builder)
  // Monster.add(color: .red, &builder)
  // Monster.addVectorOf(weapons: weaponsOffset, &builder)
  // Monster.add(equippedType: .weapon, &builder)
  // Monster.addVectorOf(paths: weaponsOffset, &builder)
  // Monster.add(equipped: axe, &builder)
  // var orc = Monster.endMonster(&builder, start: start)

  // Call `finish(offset:)` to instruct the builder that this monster is complete.
  builder.finish(offset: orc)
  // This must be called after `finish()`.
  // `sizedByteArray` returns the finished buf of type [UInt8].
  let buf = builder.sizedByteArray

  // or you can use to get an object of type Data
  let bufData = ByteBuffer(data: builder.sizedBuffer)
}


import FlatBuffers
import Foundation

func run() {
  // create a ByteBuffer(:) from an [UInt8] or Data()
  let buf = [] // Get your data

  // Get an accessor to the root object inside the buffer.
  let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
  // let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))

  let hp = monster.hp
  let mana = monster.mana
  let name = monster.name // returns an optional string

  let pos = monster.pos
  let x = pos.x
  let y = pos.y
}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")

  // start creating the weapon by calling startWeapon
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: 3, &builder)
  // end the object by passing the start point for the weapon 1
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)

  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: 5, &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)

  // Create a FlatBuffer `vector` that contains offsets to the sword and axe
  // we created above.
  let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])

  // Name of the Monster.
  let name = builder.create(string: "Orc")

  let pathOffset = fbb.createVector(ofStructs: [
    Vec3(x: 0, y: 0),
    Vec3(x: 5, y: 5),
  ])

  // startVector(len, elementSize: MemoryLayout<Offset>.size)
  // for o in offsets.reversed() {
  //   push(element: o)
  // }
  // endVector(len: len)

  let orc = Monster.createMonster(
    &builder,
    pos: Vec3(x: 1, y: 2),
    hp: 300,
    nameOffset: name,
    color: .red,
    weaponsVectorOffset: weaponsOffset,
    equippedType: .weapon,
    equippedOffset: axe,
    pathOffset: pathOffset)

  // let start = Monster.startMonster(&builder)
  // Monster.add(pos: Vec3(x: 1, y: 2), &builder)
  // Monster.add(hp: 300, &builder)
  // Monster.add(name: name, &builder)
  // Monster.add(color: .red, &builder)
  // Monster.addVectorOf(weapons: weaponsOffset, &builder)
  // Monster.add(equippedType: .weapon, &builder)
  // Monster.addVectorOf(paths: weaponsOffset, &builder)
  // Monster.add(equipped: axe, &builder)
  // var orc = Monster.endMonster(&builder, start: start)
}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")

  // start creating the weapon by calling startWeapon
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: 3, &builder)
  // end the object by passing the start point for the weapon 1
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)

  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: 5, &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)

  // Create a FlatBuffer `vector` that contains offsets to the sword and axe
  // we created above.
  let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)

  let weapon1Name = builder.create(string: "Sword")
  let weapon2Name = builder.create(string: "Axe")

  // start creating the weapon by calling startWeapon
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: 3, &builder)
  // end the object by passing the start point for the weapon 1
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)

  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: 5, &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)

  // Create a FlatBuffer `vector` that contains offsets to the sword and axe
  // we created above.
  let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])

  // Name of the Monster.
  let name = builder.create(string: "Orc")
}


import FlatBuffers
import Foundation

func run() {
  // create a ByteBuffer(:) from an [UInt8] or Data()
  let buf = [] // Get your data

  // Get an accessor to the root object inside the buffer.
  let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
  // let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))

  let hp = monster.hp
  let mana = monster.mana
  let name = monster.name // returns an optional string

  let pos = monster.pos
  let x = pos.x
  let y = pos.y

  // Get and check if the monster has an equipped item
  if monster.equippedType == .weapon {
    let _weapon = monster.equipped(type: Weapon.self)
    let name = _weapon.name // should return "Axe"
    let dmg = _weapon.damage // should return 5
  }
}


import FlatBuffers
import Foundation

func run() {
  // create a `FlatBufferBuilder`, which will be used to serialize objects
  let builder = FlatBufferBuilder(initialSize: 1024)
}


import FlatBuffers
import Foundation

func run() {
  // create a ByteBuffer(:) from an [UInt8] or Data()
  let buf = [] // Get your data

  // Get an accessor to the root object inside the buffer.
  let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
  // let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))
}


import Foundation


Package

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


main

/*
 */
import FlatBuffers
import GRPC
import Logging
import Model
import NIO
// Quieten the logs.
LoggingSystem.bootstrap {
  var handler = StreamLogHandler.standardOutput(label: $0)
  handler.logLevel = .critical
  return handler
}
func greet(name: String, client greeter: models_GreeterServiceClient) {
  // Form the request with the name, if one was provided.
  var builder = FlatBufferBuilder()
  let nameOff = builder.create(string: name)
  let root = models_HelloRequest.createHelloRequest(
    &builder,
    nameOffset: nameOff)
  builder.finish(offset: root)
  // Make the RPC call to the server.
  let sayHello = greeter
    .SayHello(Message<models_HelloRequest>(builder: &builder))
  // wait() on the response to stop the program from exiting before the response is received.
  do {
    let response = try sayHello.response.wait()
    print("Greeter SayHello received: \(response.object.message ?? "Unknown")")
  } catch {
    print("Greeter failed: \(error)")
  }
  let surname = builder.create(string: name)
  let manyRoot = models_HelloRequest.createHelloRequest(
    &builder,
    nameOffset: surname)
  builder.finish(offset: manyRoot)
  let call = greeter.SayManyHellos(Message(builder: &builder)) { message in
    print(
      "Greeter SayManyHellos received: \(message.object.message  ?? "Unknown")")
  }
  let status = try! call.status.recover { _ in .processingError }.wait()
  if status.code != .ok {
    print("RPC failed: \(status)")
  }
}
func main(args: [String]) {
  // arg0 (dropped) is the program name. We expect arg1 to be the port, and arg2 (optional) to be
  // the name sent in the request.
  let arg1 = args.dropFirst(1).first
  let arg2 = args.dropFirst(2).first
  switch (arg1.flatMap(Int.init), arg2) {
  case (.none, _):
    print("Usage: PORT [NAME]")
    exit(1)
  case let (.some(port), name):
    // Setup an `EventLoopGroup` for the connection to run on.
    //
    // See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
    let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
    // Make sure the group is shutdown when we're done with it.
    defer {
      try! group.syncShutdownGracefully()
    }
    // Configure the channel, we're not using TLS so the connection is `insecure`.
    let channel = ClientConnection.insecure(group: group)
      .connect(host: "localhost", port: port)
    // Close the connection when we're done with it.
    defer {
      try! channel.close().wait()
    }
    // Provide the connection to the generated client.
    let greeter = models_GreeterServiceClient(channel: channel)
    // Do the greeting.
    greet(name: name ?? "FlatBuffers!", client: greeter)
  }
}
main(args: CommandLine.arguments)


/*
 */
import FlatBuffers
import GRPC
import Logging
import Model
import NIO
class Greeter: models_GreeterProvider {
  var interceptors: models_GreeterServerInterceptorFactoryProtocol?
  let greetings: [String]
  init() {
    greetings = ["Hi", "Hallo", "Ciao"]
  }
  func SayHello(
    request: Message<models_HelloRequest>,
    context: StatusOnlyCallContext)
    -> EventLoopFuture<Message<models_HelloReply>>
  {
    let recipient = request.object.name ?? "Stranger"
    var builder = FlatBufferBuilder()
    let off = builder.create(string: "Hello \(recipient)")
    let root = models_HelloReply.createHelloReply(&builder, messageOffset: off)
    builder.finish(offset: root)
    return context.eventLoop
      .makeSucceededFuture(Message<models_HelloReply>(builder: &builder))
  }
  func SayManyHellos(
    request: Message<models_HelloRequest>,
    context: StreamingResponseCallContext<Message<models_HelloReply>>)
    -> EventLoopFuture<GRPCStatus>
  {
    for name in greetings {
      var builder = FlatBufferBuilder()
      let off = builder
        .create(string: "\(name) \(request.object.name ?? "Unknown")")
      let root = models_HelloReply.createHelloReply(
        &builder,
        messageOffset: off)
      builder.finish(offset: root)
      _ = context.sendResponse(Message<models_HelloReply>(builder: &builder))
    }
    return context.eventLoop.makeSucceededFuture(.ok)
  }
}
// Quieten the logs.
LoggingSystem.bootstrap {
  var handler = StreamLogHandler.standardOutput(label: $0)
  handler.logLevel = .critical
  return handler
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
  try! group.syncShutdownGracefully()
}
// Create some configuration for the server:
let configuration = Server.Configuration(
  target: .hostAndPort("localhost", 0),
  eventLoopGroup: group,
  serviceProviders: [Greeter()])
// Start the server and print its address once it has started.
let server = Server.start(configuration: configuration)
server.map {
  $0.channel.localAddress
}.whenSuccess { address in
  print("server started on port \(address!.port!)")
}
// Wait on the server's `onClose` future to stop the program from exiting.
_ = try server.flatMap {
  $0.onClose
}.wait()


// automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
// swiftformat:disable all

import FlatBuffers

public struct models_HelloReply: FlatBufferObject, Verifiable {

  static func validateVersion() { FlatBuffersVersion_2_0_0() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table

  public static func getRootAsHelloReply(bb: ByteBuffer) -> models_HelloReply { return models_HelloReply(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }

  private init(_ t: Table) { _accessor = t }
  public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }

  private enum VTOFFSET: VOffset {
    case message = 4
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }

  public var message: String? { let o = _accessor.offset(VTOFFSET.message.v); return o == 0 ? nil : _accessor.string(at: o) }
  public var messageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.message.v) }
  public static func startHelloReply(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
  public static func add(message: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: message, at: VTOFFSET.message.p) }
  public static func endHelloReply(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createHelloReply(
    _ fbb: inout FlatBufferBuilder,
    messageOffset message: Offset = Offset()
  ) -> Offset {
    let __start = models_HelloReply.startHelloReply(&fbb)
    models_HelloReply.add(message: message, &fbb)
    return models_HelloReply.endHelloReply(&fbb, start: __start)
  }

  public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
    var _v = try verifier.visitTable(at: position)
    try _v.visit(field: VTOFFSET.message.p, fieldName: "message", required: false, type: ForwardOffset<String>.self)
    _v.finish()
  }
}

extension models_HelloReply: Encodable {

  enum CodingKeys: String, CodingKey {
    case message = "message"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encodeIfPresent(message, forKey: .message)
  }
}

public struct models_HelloRequest: FlatBufferObject, Verifiable {

  static func validateVersion() { FlatBuffersVersion_2_0_0() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table

  public static func getRootAsHelloRequest(bb: ByteBuffer) -> models_HelloRequest { return models_HelloRequest(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }

  private init(_ t: Table) { _accessor = t }
  public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }

  private enum VTOFFSET: VOffset {
    case name = 4
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }

  public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
  public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
  public static func startHelloRequest(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
  public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
  public static func endHelloRequest(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createHelloRequest(
    _ fbb: inout FlatBufferBuilder,
    nameOffset name: Offset = Offset()
  ) -> Offset {
    let __start = models_HelloRequest.startHelloRequest(&fbb)
    models_HelloRequest.add(name: name, &fbb)
    return models_HelloRequest.endHelloRequest(&fbb, start: __start)
  }

  public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
    var _v = try verifier.visitTable(at: position)
    try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset<String>.self)
    _v.finish()
  }
}

extension models_HelloRequest: Encodable {

  enum CodingKeys: String, CodingKey {
    case name = "name"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encodeIfPresent(name, forKey: .name)
  }
}


greeter.grpc

// Generated GRPC code for FlatBuffers swift!
/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift
/// in case of an issue please open github issue, though it would be maintained
// swiftlint:disable all
// swiftformat:disable all
import Foundation
import GRPC
import NIO
import NIOHTTP1
import FlatBuffers
public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {}
public extension GRPCFlatBufPayload {
  init(serializedByteBuffer: inout NIO.ByteBuffer) throws {
    self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes))
  }
  func serialize(into buffer: inout NIO.ByteBuffer) throws {
    let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size))
    buffer.writeBytes(buf)
  }
}
extension Message: GRPCFlatBufPayload {}
/// Usage: instantiate models_GreeterServiceClient, then call methods of this protocol to make API calls.
public protocol models_GreeterClientProtocol: GRPCClient {
  var serviceName: String { get }
  var interceptors: models_GreeterClientInterceptorFactoryProtocol? { get }
  func SayHello(
    _ request: Message<models_HelloRequest>
    , callOptions: CallOptions?
  ) -> UnaryCall<Message<models_HelloRequest>, Message<models_HelloReply>>
  func SayManyHellos(
    _ request: Message<models_HelloRequest>
    , callOptions: CallOptions?,
  ) -> ServerStreamingCall<Message<models_HelloRequest>, Message<models_HelloReply>>
}
extension models_GreeterClientProtocol {
  public var serviceName: String { "models.Greeter" }
  public func SayHello(
    _ request: Message<models_HelloRequest>
    , callOptions: CallOptions? = nil
  ) -> UnaryCall<Message<models_HelloRequest>, Message<models_HelloReply>> {
    return self.makeUnaryCall(
      path: "/models.Greeter/SayHello",
      request: request,
      callOptions: callOptions ?? self.defaultCallOptions,
      interceptors: self.interceptors?.makeSayHelloInterceptors() ?? []
    )
  }
  public func SayManyHellos(
    _ request: Message<models_HelloRequest>
    , callOptions: CallOptions? = nil,
  ) -> ServerStreamingCall<Message<models_HelloRequest>, Message<models_HelloReply>> {
    return self.makeServerStreamingCall(
      path: "/models.Greeter/SayManyHellos",
      request: request,
      callOptions: callOptions ?? self.defaultCallOptions,
      interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [],
      handler: handler
    )
  }
}
public protocol models_GreeterClientInterceptorFactoryProtocol {
  /// - Returns: Interceptors to use when invoking 'SayHello'.
  func makeSayHelloInterceptors() -> [ClientInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
  /// - Returns: Interceptors to use when invoking 'SayManyHellos'.
  func makeSayManyHellosInterceptors() -> [ClientInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
}
public final class models_GreeterServiceClient: models_GreeterClientProtocol {
  public let channel: GRPCChannel
  public var defaultCallOptions: CallOptions
  public var interceptors: models_GreeterClientInterceptorFactoryProtocol?
  public init(
    channel: GRPCChannel,
    defaultCallOptions: CallOptions = CallOptions(),
    interceptors: models_GreeterClientInterceptorFactoryProtocol? = nil
  ) {
    self.channel = channel
    self.defaultCallOptions = defaultCallOptions
    self.interceptors = interceptors
  }
}
public protocol models_GreeterProvider: CallHandlerProvider {
  var interceptors: models_GreeterServerInterceptorFactoryProtocol? { get }
  func SayHello(request: Message<models_HelloRequest>, context: StatusOnlyCallContext) -> EventLoopFuture<Message<models_HelloReply>>
  func SayManyHellos(request: Message<models_HelloRequest>, context: StreamingResponseCallContext<Message<models_HelloReply>>) -> EventLoopFuture<GRPCStatus>
}
public extension models_GreeterProvider {
  var serviceName: Substring { return "models.Greeter" }
  func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? {
    switch name {
    case "SayHello":
    return UnaryServerHandler(
      context: context,
      requestDeserializer: GRPCPayloadDeserializer<Message<models_HelloRequest>>(),
      responseSerializer: GRPCPayloadSerializer<Message<models_HelloReply>>(),
      interceptors: self.interceptors?.makeSayHelloInterceptors() ?? [],
      userFunction: self.SayHello(request:context:))
    case "SayManyHellos":
    return ServerStreamingServerHandler(
      context: context,
      requestDeserializer: GRPCPayloadDeserializer<Message<models_HelloRequest>>(),
      responseSerializer: GRPCPayloadSerializer<Message<models_HelloReply>>(),
      interceptors: self.interceptors?.makeSayManyHellosInterceptors() ?? [],
      userFunction: self.SayManyHellos(request:context:))
    default: return nil;
    }
  }
}
public protocol models_GreeterServerInterceptorFactoryProtocol {
  /// - Returns: Interceptors to use when handling 'SayHello'.
  ///   Defaults to calling `self.makeInterceptors()`.
  func makeSayHelloInterceptors() -> [ServerInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
  /// - Returns: Interceptors to use when handling 'SayManyHellos'.
  ///   Defaults to calling `self.makeInterceptors()`.
  func makeSayManyHellosInterceptors() -> [ServerInterceptor<Message<models_HelloRequest>, Message<models_HelloReply>>]
}


TFLBertTokenizerTest

class TFLBertTokenizerTest: XCTestCase {
  static let bundle = Bundle(for: TFLBertTokenizerTest.self)
  static let mobileBertVocabPath = bundle.path(forResource: "vocab", ofType: "txt")!
  func testInitBertTokenizerFromPath() {
    let bertTokenizer = TFLBertTokenizer(vocabPath: TFLBertTokenizerTest.mobileBertVocabPath)
    XCTAssertNotNil(bertTokenizer)
    let tokens = bertTokenizer.tokens(fromInput: "i'm questionansweraskask")
    XCTAssertEqual(tokens, ["i", "'", "m", "question", "##ans", "##wer", "##ask", "##ask"])
    let ids = bertTokenizer.ids(fromTokens: tokens)
    XCTAssertEqual(ids, [1045, 1005, 1049, 3160, 6962, 13777, 19895, 19895])
  }
  func testInitBertTokenizerFromVocab() {
    let bertTokenizer = TFLBertTokenizer(vocab: ["hell", "##o", "wor", "##ld", "there"])
    XCTAssertNotNil(bertTokenizer)
    let tokens = bertTokenizer.tokens(fromInput: "hello there hello world")
    XCTAssertEqual(tokens, ["hell", "##o", "there", "hell", "##o", "wor", "##ld"])
    let ids = bertTokenizer.ids(fromTokens: tokens)
    XCTAssertEqual(ids, [0, 1, 4, 0, 1, 2, 3])
  }
}


TFLSentencepieceTokenizerTest

class TFLSentencepieceTokenizerTest: XCTestCase {
  static let bundle = Bundle(for: TFLSentencepieceTokenizerTest.self)
  static let spModelPath = bundle.path(forResource: "30k-clean", ofType: "model")!
  func testInitSentenpieceTokenizerFromPath() {
    let spTokenizer = TFLSentencepieceTokenizer(
      modelPath: TFLSentencepieceTokenizerTest.spModelPath)
    XCTAssertNotNil(spTokenizer)
    let tokens = spTokenizer.tokens(fromInput: "good morning, i'm your teacher.\n")
    XCTAssertEqual(tokens, ["▁good", "▁morning", ",", "▁i", "'", "m", "▁your", "▁teacher", "."])
    let ids = spTokenizer.ids(fromTokens: tokens)
    XCTAssertEqual(ids, [254, 959, 15, 31, 22, 79, 154, 2197, 9])
  }
}


TFLBertNLClassifierTest

class TFLBertNLClassifierTest: XCTestCase {
  static let bundle = Bundle(for: TFLBertNLClassifierTest.self)
  static let bertModelPath = bundle.path(forResource: "test_model_nl_classifier_bert", ofType: "tflite")!
  func testClassifyPositiveResult() {
    let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: TFLBertNLClassifierTest.bertModelPath)
    XCTAssertNotNil(bertNLClassifier)
    let categories = bertNLClassifier.classify(text: "it's a charming and often affecting journey")
    XCTAssertGreaterThan(categories["positive"]!.doubleValue, categories["negative"]!.doubleValue)
  }
  func testClassifyNegativeResult() {
    let bertNLClassifier = TFLBertNLClassifier.bertNLClassifier(
      modelPath: TFLBertNLClassifierTest.bertModelPath)
    XCTAssertNotNil(bertNLClassifier)
    let categories = bertNLClassifier.classify(text: "unflinchingly bleak and desperate")
    XCTAssertGreaterThan(categories["negative"]!.doubleValue, categories["positive"]!.doubleValue)
  }
}


TFLNLClassifierTest

class TFLNLClassifierTest: XCTestCase {
  static let bundle = Bundle(for: TFLNLClassifierTest.self)
  static let modelPath = bundle.path(
    forResource: "test_model_nl_classifier_with_regex_tokenizer",
    ofType: "tflite")!
  var modelOptions:TFLNLClassifierOptions!;
  override func setUp() {
    modelOptions = TFLNLClassifierOptions()
    modelOptions.inputTensorName = "input_text"
    modelOptions.outputScoreTensorName = "probability"
  }
  func testClassifyPositiveResult() {
    let nlClassifier = TFLNLClassifier.nlClassifier(
      modelPath: TFLNLClassifierTest.modelPath,
      options: modelOptions)
    XCTAssertNotNil(nlClassifier)
    let categories = nlClassifier.classify(
      text: "This is the best movie I’ve seen in recent years. Strongly recommend it!")
    XCTAssertGreaterThan(categories["Positive"]!.doubleValue, categories["Negative"]!.doubleValue)
  }
   func testClassifyNegativeResult() {
     let nlClassifier = TFLNLClassifier.nlClassifier(
       modelPath: TFLNLClassifierTest.modelPath,
       options: modelOptions)
     XCTAssertNotNil(nlClassifier)
     let categories = nlClassifier.classify(text: "What a waste of my time.")
     XCTAssertGreaterThan(categories["Negative"]!.doubleValue, categories["Positive"]!.doubleValue)
   }
}


TFLBertQuestionAnswererTest

class TFLBertQuestionAnswererTest: XCTestCase {
  static let bundle = Bundle(for: TFLBertQuestionAnswererTest.self)
  static let mobileBertModelPath = bundle.path(forResource: "mobilebert_with_metadata", ofType: "tflite")!
  static let albertModelPath = bundle.path(forResource: "albert_with_metadata", ofType: "tflite")!
  static let context = """
    The role of teacher is often formal and ongoing, carried out at a school or other place of
    formal education. In many countries, a person who wishes to become a teacher must first obtain
     specified professional qualifications or credentials from a university or college. These
    professional qualifications may include the study of pedagogy, the science of teaching.
    Teachers, like other professionals, may have to continue their education after they qualify,
    a process known as continuing professional development. Teachers may use a lesson plan to
    facilitate student learning, providing a course of study which is called the curriculum.
    """
  static let question = "What is a course of study called?"
  static let answer = "the curriculum."
  func testInitMobileBert() {
    let mobileBertAnswerer = TFLBertQuestionAnswerer.questionAnswerer(
      modelPath: TFLBertQuestionAnswererTest.mobileBertModelPath)
    XCTAssertNotNil(mobileBertAnswerer)
    let answers = mobileBertAnswerer.answer(
      context: TFLBertQuestionAnswererTest.context, question: TFLBertQuestionAnswererTest.question)
    XCTAssertNotNil(answers)
    XCTAssertEqual(answers[0].text, TFLBertQuestionAnswererTest.answer)
  }
  func testInitAlbert() {
    let albertAnswerer = TFLBertQuestionAnswerer.questionAnswerer(
      modelPath: TFLBertQuestionAnswererTest.albertModelPath)
    XCTAssertNotNil(albertAnswerer)
    let answers = albertAnswerer.answer(
      context: TFLBertQuestionAnswererTest.context, question: TFLBertQuestionAnswererTest.question)
    XCTAssertNotNil(answers)
    XCTAssertEqual(answers[0].text, TFLBertQuestionAnswererTest.answer)
  }
}


s

infix operator •: AdditionPrecedence
func • (a: Int, b: Int) -> Int {
  return a * b
}
func g(a: Int) -> Int{
  return a + 1
}
let i = g(a: 1 • 2)


import Swift

var s: [Int] = [1, 2, 3, 4]

func f() {
  for i in 0..<4 {
    print(s[i])
  }
}

f()


Package

// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
  name: "nanopb",
  products: [
    .library(
      name: "nanopb",
      targets: ["nanopb"]
    )
  ],

  targets: [
    .target(
      name: "nanopb",
      path: ".",
      sources: [
        "pb.h",
        "pb_common.h",
        "pb_common.c",
        "pb_decode.h",
        "pb_decode.c",
        "pb_encode.h",
        "pb_encode.c"
      ],
      publicHeadersPath: "spm_headers",
      cSettings: [
        .define("PB_FIELD_32BIT", to: "1"),
        .define("PB_NO_PACKED_STRUCTS", to: "1"),
        .define("PB_ENABLE_MALLOC", to: "1"),
      ]
    ),
    .testTarget(
      name: "swift-test",
      dependencies: [
        "nanopb",
      ],
      path: "spm-test/swift",
      cSettings: [
        .headerSearchPath("../"),
        .define("PB_FIELD_32BIT", to: "1"),
        .define("PB_NO_PACKED_STRUCTS", to: "1"),
        .define("PB_ENABLE_MALLOC", to: "1"),
      ]
    ),
    .testTarget(
      name: "objc-test",
      dependencies: [
        "nanopb",
      ],
      path: "spm-test/objc",
      cSettings: [
        .headerSearchPath("../"),
        .define("PB_FIELD_32BIT", to: "1"),
        .define("PB_NO_PACKED_STRUCTS", to: "1"),
        .define("PB_ENABLE_MALLOC", to: "1"),
      ]
    )
  ]
)


main

import nanopb