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>>]
}


// 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_23_5_9() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table

  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_23_5_9() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table

  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)
  }
}


main

/*
 */
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()


/*
 */
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)


// automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
// swiftformat:disable all
import FlatBuffers
public enum MyGame_Sample_Color: Int8, Enum, Verifiable {
  public typealias T = Int8
  public static var byteSize: Int { return MemoryLayout<Int8>.size }
  public var value: Int8 { return self.rawValue }
  case red = 0
  case green = 1
  case blue = 2
  public static var max: MyGame_Sample_Color { return .blue }
  public static var min: MyGame_Sample_Color { return .red }
}
public enum MyGame_Sample_Equipment: UInt8, UnionEnum {
  public typealias T = UInt8
  public init?(value: T) {
    self.init(rawValue: value)
  }
  public static var byteSize: Int { return MemoryLayout<UInt8>.size }
  public var value: UInt8 { return self.rawValue }
  case none_ = 0
  case weapon = 1
  public static var max: MyGame_Sample_Equipment { return .weapon }
  public static var min: MyGame_Sample_Equipment { return .none_ }
}
public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable {
  static func validateVersion() { FlatBuffersVersion_23_5_9() }
  private var _x: Float32
  private var _y: Float32
  private var _z: Float32
  public init(_ bb: ByteBuffer, o: Int32) {
    let _accessor = Struct(bb: bb, position: o)
    _x = _accessor.readBuffer(of: Float32.self, at: 0)
    _y = _accessor.readBuffer(of: Float32.self, at: 4)
    _z = _accessor.readBuffer(of: Float32.self, at: 8)
  }
  public init(x: Float32, y: Float32, z: Float32) {
    _x = x
    _y = y
    _z = z
  }
  public init() {
    _x = 0.0
    _y = 0.0
    _z = 0.0
  }
  public var x: Float32 { _x }
  public var y: Float32 { _y }
  public var z: Float32 { _z }
  public static func verify<T>(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable {
    try verifier.inBuffer(position: position, of: MyGame_Sample_Vec3.self)
  }
}
public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject {
  static func validateVersion() { FlatBuffersVersion_23_5_9() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Struct
  public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) }
  public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) }
}
public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable {
  static func validateVersion() { FlatBuffersVersion_23_5_9() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table
  private init(_ t: Table) { _accessor = t }
  public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
  private enum VTOFFSET: VOffset {
    case pos = 4
    case mana = 6
    case hp = 8
    case name = 10
    case inventory = 14
    case color = 16
    case weapons = 18
    case equippedType = 20
    case equipped = 22
    case path = 24
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }
  public var pos: MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Sample_Vec3.self, at: o) }
  public var mutablePos: MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: o + _accessor.postion) }
  public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) }
  public var hasWeapons: Bool { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? false : true }
  public var weaponsCount: Int32 { let o = _accessor.offset(VTOFFSET.weapons.v); return o == 0 ? 0 : _accessor.vector(count: o) }
  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)) }
  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_ }
  public func equipped<T: FlatbuffersInitializable>(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.equipped.v); return o == 0 ? nil : _accessor.union(o) }
  public var hasPath: Bool { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? false : true }
  public var pathCount: Int32 { let o = _accessor.offset(VTOFFSET.path.v); return o == 0 ? 0 : _accessor.vector(count: o) }
  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) }
  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) }
  public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 11) }
  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) }
  public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) }
  public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) }
  public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
  public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
  public static func add(color: MyGame_Sample_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) }
  public static func addVectorOf(weapons: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: weapons, at: VTOFFSET.weapons.p) }
  public static func add(equippedType: MyGame_Sample_Equipment, _ fbb: inout FlatBufferBuilder) { fbb.add(element: equippedType.rawValue, def: 0, at: VTOFFSET.equippedType.p) }
  public static func add(equipped: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: equipped, at: VTOFFSET.equipped.p) }
  public static func addVectorOf(path: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: path, at: VTOFFSET.path.p) }
  public static func startVectorOfPath(_ size: Int, in builder: inout FlatBufferBuilder) {
    builder.startVector(size * MemoryLayout<MyGame_Sample_Vec3>.size, elementSize: MemoryLayout<MyGame_Sample_Vec3>.alignment)
  }
  public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createMonster(
    _ fbb: inout FlatBufferBuilder,
    pos: MyGame_Sample_Vec3? = nil,
    mana: Int16 = 150,
    hp: Int16 = 100,
    nameOffset name: Offset = Offset(),
    inventoryVectorOffset inventory: Offset = Offset(),
    color: MyGame_Sample_Color = .blue,
    weaponsVectorOffset weapons: Offset = Offset(),
    equippedType: MyGame_Sample_Equipment = .none_,
    equippedOffset equipped: Offset = Offset(),
    pathVectorOffset path: Offset = Offset()
  ) -> Offset {
    let __start = MyGame_Sample_Monster.startMonster(&fbb)
    MyGame_Sample_Monster.add(pos: pos, &fbb)
    MyGame_Sample_Monster.add(mana: mana, &fbb)
    MyGame_Sample_Monster.add(hp: hp, &fbb)
    MyGame_Sample_Monster.add(name: name, &fbb)
    MyGame_Sample_Monster.addVectorOf(inventory: inventory, &fbb)
    MyGame_Sample_Monster.add(color: color, &fbb)
    MyGame_Sample_Monster.addVectorOf(weapons: weapons, &fbb)
    MyGame_Sample_Monster.add(equippedType: equippedType, &fbb)
    MyGame_Sample_Monster.add(equipped: equipped, &fbb)
    MyGame_Sample_Monster.addVectorOf(path: path, &fbb)
    return MyGame_Sample_Monster.endMonster(&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.pos.p, fieldName: "pos", required: false, type: MyGame_Sample_Vec3.self)
    try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self)
    try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self)
    try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: false, type: ForwardOffset<String>.self)
    try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset<Vector<UInt8, UInt8>>.self)
    try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Sample_Color.self)
    try _v.visit(field: VTOFFSET.weapons.p, fieldName: "weapons", required: false, type: ForwardOffset<Vector<ForwardOffset<MyGame_Sample_Weapon>, MyGame_Sample_Weapon>>.self)
    try _v.visit(unionKey: VTOFFSET.equippedType.p, unionField: VTOFFSET.equipped.p, unionKeyName: "equippedType", fieldName: "equipped", required: false, completion: { (verifier, key: MyGame_Sample_Equipment, pos) in
      switch key {
      case .none_:
        break // NOTE - SWIFT doesnt support none
      case .weapon:
        try ForwardOffset<MyGame_Sample_Weapon>.verify(&verifier, at: pos, of: MyGame_Sample_Weapon.self)
      }
    })
    try _v.visit(field: VTOFFSET.path.p, fieldName: "path", required: false, type: ForwardOffset<Vector<MyGame_Sample_Vec3, MyGame_Sample_Vec3>>.self)
    _v.finish()
  }
}
public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable {
  static func validateVersion() { FlatBuffersVersion_23_5_9() }
  public var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table
  private init(_ t: Table) { _accessor = t }
  public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
  private enum VTOFFSET: VOffset {
    case name = 4
    case damage = 6
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }
  public var name: String? { let o = _accessor.offset(VTOFFSET.name.v); return o == 0 ? nil : _accessor.string(at: o) }
  public var nameSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.name.v) }
  public var damage: Int16 { let o = _accessor.offset(VTOFFSET.damage.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) }
  public static func startWeapon(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
  public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) }
  public static func add(damage: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: damage, def: 0, at: VTOFFSET.damage.p) }
  public static func endWeapon(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createWeapon(
    _ fbb: inout FlatBufferBuilder,
    nameOffset name: Offset = Offset(),
    damage: Int16 = 0
  ) -> Offset {
    let __start = MyGame_Sample_Weapon.startWeapon(&fbb)
    MyGame_Sample_Weapon.add(name: name, &fbb)
    MyGame_Sample_Weapon.add(damage: damage, &fbb)
    return MyGame_Sample_Weapon.endWeapon(&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)
    try _v.visit(field: VTOFFSET.damage.p, fieldName: "damage", required: false, type: Int16.self)
    _v.finish()
  }
}


/*
 */
import FlatBuffers
typealias Monster = MyGame_Sample_Monster
typealias Weapon = MyGame_Sample_Weapon
typealias Color = MyGame_Sample_Color
typealias Vec3 = MyGame_Sample_Vec3
func main() {
  let expectedDMG: [Int16] = [3, 5]
  let expectedNames = ["Sword", "Axe"]
  var builder = FlatBufferBuilder(initialSize: 1024)
  let weapon1Name = builder.create(string: expectedNames[0])
  let weapon2Name = builder.create(string: expectedNames[1])
  let weapon1Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon1Name, &builder)
  Weapon.add(damage: expectedDMG[0], &builder)
  let sword = Weapon.endWeapon(&builder, start: weapon1Start)
  let weapon2Start = Weapon.startWeapon(&builder)
  Weapon.add(name: weapon2Name, &builder)
  Weapon.add(damage: expectedDMG[1], &builder)
  let axe = Weapon.endWeapon(&builder, start: weapon2Start)
  let name = builder.create(string: "Orc")
  let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  let inventoryOffset = builder.createVector(inventory)
  let weaponsOffset = builder.createVector(ofOffsets: [sword, axe])
  let orc = Monster.createMonster(
    &builder,
    pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3),
    hp: 300,
    nameOffset: name,
    inventoryVectorOffset: inventoryOffset,
    color: .red,
    weaponsVectorOffset: weaponsOffset,
    equippedType: .weapon,
    equippedOffset: axe)
  builder.finish(offset: orc)
  var buf = ByteBuffer(bytes: builder.sizedByteArray)
  let monster: Monster = try! getCheckedRoot(byteBuffer: &buffer)
  assert(monster.mana == 150)
  assert(monster.hp == 300)
  assert(monster.name == "Orc")
  assert(monster.color == MyGame.Sample.Color.red)
  assert(monster.pos != nil)
  assert(monster.mutablePos != nil)
  for i in 0..<monster.inventoryCount {
    assert(i == monster.inventory(at: i))
  }
  for i in 0..<monster.weaponsCount {
    let weap = monster.weapons(at: i)
    let index = Int(i)
    assert(weap?.damage == expectedDMG[index])
    assert(weap?.name == expectedNames[index])
  }
  assert(monster.equippedType == .weapon)
  let equipped = monster.equipped(type: Weapon.self)
  assert(equipped?.name == "Axe")
  assert(equipped?.damage == 5)
  print("Monster Object is Verified")
}


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_23_5_9() {}


TableVerifier

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// `TableVerifier` verifies a table object is within a provided memory.
/// It checks if all the objects for a specific generated table, are within
/// the bounds of the buffer, aligned.
public struct TableVerifier {
  /// position of current table in `ByteBuffer`
  fileprivate var _position: Int
  /// Current VTable position
  fileprivate var _vtable: Int
  /// Length of current VTable
  fileprivate var _vtableLength: Int
  /// `Verifier` object created in the base verifable call.
  fileprivate var _verifier: Verifier
  /// Creates a `TableVerifier` verifier that allows the Flatbuffer object
  /// to verify the buffer before accessing any of the data.
  ///
  /// - Parameters:
  ///   - position: Current table Position
  ///   - vtable: Current `VTable` position
  ///   - vtableLength: Current `VTable` length
  ///   - verifier: `Verifier` Object  that caches the data of the verifiable object
  internal init(
    position: Int,
    vtable: Int,
    vtableLength: Int,
    verifier: inout Verifier)
  {
    _position = position
    _vtable = vtable
    _vtableLength = vtableLength
    _verifier = verifier
  }
  /// Dereference the current object position from the `VTable`
  /// - Parameter field: Current VTable refrence to  position.
  /// - Throws: A `FlatbuffersErrors` incase the voffset is not aligned/outOfBounds/apparentSizeTooLarge
  /// - Returns: An optional position for current field
  internal mutating func dereference(_ field: VOffset) throws -> Int? {
    if field >= _vtableLength {
      return nil
    }
    /// Reading the offset for the field needs to be read.
    let offset: VOffset = try _verifier.getValue(
      at: Int(clamping: _vtable &+ Int(field)))
    if offset > 0 {
      return Int(clamping: _position &+ Int(offset))
    }
    return nil
  }
  /// Visits all the fields within the table to validate the integrity
  /// of the data
  /// - Parameters:
  ///   - field: voffset of the current field to be read
  ///   - fieldName: fieldname to report data Errors.
  ///   - required: If the field has to be available in the buffer
  ///   - type: Type of field to be read
  /// - Throws: A `FlatbuffersErrors` where the field is corrupt
  public mutating func visit<T>(
    field: VOffset,
    fieldName: String,
    required: Bool,
    type: T.Type) throws where T: Verifiable
  {
    let derefValue = try dereference(field)
    if let value = derefValue {
      try T.verify(&_verifier, at: value, of: T.self)
      return
    }
    if required {
      throw FlatbuffersErrors.requiredFieldDoesntExist(
        position: field,
        name: fieldName)
    }
  }
  /// Visits all the fields for a union object within the table to
  /// validate the integrity of the data
  /// - Parameters:
  ///   - key: Current Key Voffset
  ///   - field: Current field Voffset
  ///   - unionKeyName: Union key name
  ///   - fieldName: Field key name
  ///   - required: indicates if an object is required to be present
  ///   - completion: Completion is a handler that WILL be called in the generated
  /// - Throws: A `FlatbuffersErrors` where the field is corrupt
  public mutating func visit<T>(
    unionKey key: VOffset,
    unionField field: VOffset,
    unionKeyName: String,
    fieldName: String,
    required: Bool,
    where T: UnionEnum
  {
    let keyPos = try dereference(key)
    let valPos = try dereference(field)
    if keyPos == nil && valPos == nil {
      if required {
        throw FlatbuffersErrors.requiredFieldDoesntExist(
          position: key,
          name: unionKeyName)
      }
      return
    }
    if let _key = keyPos,
       let _val = valPos
    {
      /// verifiying that the key is within the buffer
      try T.T.verify(&_verifier, at: _key, of: T.T.self)
      guard let _enum = try T.init(value: _verifier._buffer.read(
        def: T.T.self,
        position: _key)) else
      {
        throw FlatbuffersErrors.unknownUnionCase
      }
      /// we are assuming that Unions will always be of type Uint8
      try completion(
        &_verifier,
        _enum,
        _val)
      return
    }
    throw FlatbuffersErrors.valueNotFound(
      key: keyPos,
      keyName: unionKeyName,
      field: valPos,
      fieldName: fieldName)
  }
  /// Visits and validates all the objects within a union vector
  /// - Parameters:
  ///   - key: Current Key Voffset
  ///   - field: Current field Voffset
  ///   - unionKeyName: Union key name
  ///   - fieldName: Field key name
  ///   - required: indicates if an object is required to be present
  ///   - completion: Completion is a handler that WILL be called in the generated
  /// - Throws: A `FlatbuffersErrors` where the field is corrupt
  public mutating func visitUnionVector<T>(
    unionKey key: VOffset,
    unionField field: VOffset,
    unionKeyName: String,
    fieldName: String,
    required: Bool,
    where T: UnionEnum
  {
    let keyVectorPosition = try dereference(key)
    let offsetVectorPosition = try dereference(field)
    if let keyPos = keyVectorPosition,
       let valPos = offsetVectorPosition
    {
      try UnionVector<T>.verify(
        &_verifier,
        keyPosition: keyPos,
        fieldPosition: valPos,
        unionKeyName: unionKeyName,
        fieldName: fieldName,
        completion: completion)
      return
    }
    if required {
      throw FlatbuffersErrors.requiredFieldDoesntExist(
        position: field,
        name: fieldName)
    }
  }
  /// Finishs the current Table verifier, and subtracts the current
  /// table from the incremented depth.
  public mutating func finish() {
    _verifier.finish()
  }
}


FlatBufferObject

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// NativeStruct is a protocol that indicates if the struct is a native `swift` struct
/// since now we will be serializing native structs into the buffer.
public protocol NativeStruct {}
/// FlatbuffersInitializable is a protocol that allows any object to be
/// Initialized from a ByteBuffer
public protocol FlatbuffersInitializable {
  /// Any flatbuffers object that confirms to this protocol is going to be
  /// initializable through this initializer
  init(_ bb: ByteBuffer, o: Int32)
}
/// FlatbufferObject structures all the Flatbuffers objects
public protocol FlatBufferObject: FlatbuffersInitializable {
  var __buffer: ByteBuffer! { get }
}
/// ``ObjectAPIPacker`` is a protocol that allows object to pack and unpack from a
/// ``NativeObject`` to a flatbuffers Object and vice versa.
public protocol ObjectAPIPacker {
  /// associatedtype to the object that should be unpacked.
  associatedtype T
  /// ``pack(_:obj:)-3ptws`` tries to pacs the variables of a native Object into the `ByteBuffer` by using
  /// a FlatBufferBuilder
  /// - Parameters:
  ///   - builder: FlatBufferBuilder that will host incoming data
  ///   - obj: Object of associatedtype to the current implementer
  ///
  /// ``pack(_:obj:)-3ptws`` can be called by passing through an already initialized ``FlatBufferBuilder``
  /// or it can be called by using the public API that will create a new ``FlatBufferBuilder``
  static func pack(_ builder: inout FlatBufferBuilder, obj: inout T?) -> Offset
  /// ``pack(_:obj:)-20ipk`` packs the variables of a native Object into the `ByteBuffer` by using
  /// the FlatBufferBuilder
  /// - Parameters:
  ///   - builder: FlatBufferBuilder that will host incoming data
  ///   - obj: Object of associatedtype to the current implementer
  ///
  /// ``pack(_:obj:)-20ipk`` can be called by passing through an already initialized ``FlatBufferBuilder``
  /// or it can be called by using the public API that will create a new ``FlatBufferBuilder``
  static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset
  /// ``unpack()`` unpacks a ``FlatBuffers`` object into a Native swift object.
  mutating func unpack() -> T
}


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
  }
}


Message

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// FlatBufferGRPCMessage protocol that should allow us to invoke
/// initializers directly from the GRPC generated code
public protocol FlatBufferGRPCMessage {
  /// Raw pointer which would be pointing to the beginning of the readable bytes
  var rawPointer: UnsafeMutableRawPointer { get }
  /// Size of readable bytes in the buffer
  var size: Int { get }
  init(byteBuffer: ByteBuffer)
}
/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the
/// GRPC library
public struct Message<T: FlatBufferObject>: FlatBufferGRPCMessage {
  internal var buffer: ByteBuffer
  /// Returns the an object of type T that would be  read from the buffer
  public var object: T {
    T.init(
      buffer,
      o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) +
        Int32(buffer.reader))
  }
  public var rawPointer: UnsafeMutableRawPointer {
    buffer.memory.advanced(by: buffer.reader) }
  public var size: Int { Int(buffer.size) }
  /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over
  /// GRPC
  /// - Parameter byteBuffer: Flatbuffer ByteBuffer object
  public init(byteBuffer: ByteBuffer) {
    buffer = byteBuffer
  }
  /// from the builder
  /// - Parameter builder: FlatbufferBuilder that has the bytes created in
  /// - Note: Use  `builder.finish(offset)` before passing the builder without prefixing anything to it
  public init(builder: inout FlatBufferBuilder) {
    buffer = builder.sizedBuffer
    builder.clear()
  }
}


FlatBuffersUtils

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// FlatBuffersUtils hosts some utility functions that might be useful
public enum FlatBuffersUtils {
  /// Gets the size of the prefix
  /// - Parameter bb: Flatbuffer object
  public static func getSizePrefix(bb: ByteBuffer) -> Int32 {
    bb.read(def: Int32.self, position: bb.reader)
  }
  /// Removes the prefix by duplicating the Flatbuffer this call is expensive since its
  /// creates a new buffer use `readPrefixedSizeCheckedRoot` instead
  /// unless a completely new buffer is required
  /// - Parameter bb: Flatbuffer object
  ///
  ///
  public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer {
    bb.duplicate(removing: MemoryLayout<Int32>.size)
  }
}


VeriferOptions

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// `VerifierOptions` is a set of options to verify a flatbuffer
public struct VerifierOptions {
  /// Maximum `Apparent` size if the buffer can be expanded into a DAG tree
  internal var _maxApparentSize: UOffset
  /// Maximum table count allowed in a buffer
  internal var _maxTableCount: UOffset
  /// Maximum depth allowed in a buffer
  internal var _maxDepth: UOffset
  /// Ignoring missing null terminals in strings
  internal var _ignoreMissingNullTerminators: Bool
  /// initializes the set of options for the verifier
  /// - Parameters:
  ///   - maxDepth: Maximum depth allowed in a buffer
  ///   - maxTableCount: Maximum table count allowed in a buffer
  ///   - maxApparentSize: Maximum `Apparent` size if the buffer can be expanded into a DAG tree
  ///   - ignoreMissingNullTerminators: Ignoring missing null terminals in strings *Currently not supported in swift*
  public init(
    maxDepth: UOffset = 64,
    maxTableCount: UOffset = 1000000,
    maxApparentSize: UOffset = 1 << 31,
    ignoreMissingNullTerminators: Bool = false)
  {
    _maxDepth = maxDepth
    _maxTableCount = maxTableCount
    _maxApparentSize = maxApparentSize
    _ignoreMissingNullTerminators = ignoreMissingNullTerminators
  }
}


String+extension

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
extension String: Verifiable {
  /// Verifies that the current value is which the bounds of the buffer, and if
  /// the current `Value` is aligned properly
  /// - Parameters:
  ///   - verifier: Verifier that hosts the buffer
  ///   - position: Current position within the buffer
  ///   - type: The type of the object to be verified
  /// - Throws: Errors coming from `inBuffer`, `missingNullTerminator` and `outOfBounds`
  public static func verify<T>(
    _ verifier: inout Verifier,
    at position: Int,
    of type: T.Type) throws where T: Verifiable
  {
    let range = try String.verifyRange(&verifier, at: position, of: UInt8.self)
    /// Safe &+ since we already check for overflow in verify range
    let stringLen = range.start &+ range.count
    if stringLen >= verifier.capacity {
      throw FlatbuffersErrors.outOfBounds(
        position: UInt(clamping: stringLen.magnitude),
        end: verifier.capacity)
    }
    let isNullTerminated = verifier._buffer.read(
      def: UInt8.self,
      position: stringLen) == 0
    if !verifier._options._ignoreMissingNullTerminators && !isNullTerminated {
      let str = verifier._buffer.readString(at: range.start, count: range.count)
      throw FlatbuffersErrors.missingNullTerminator(
        position: position,
        str: str)
    }
  }
}
extension String: FlatbuffersInitializable {
  /// Initailizes a string from a Flatbuffers ByteBuffer
  /// - Parameters:
  ///   - bb: ByteBuffer containing the readable string
  ///   - o: Current position
  public init(_ bb: ByteBuffer, o: Int32) {
    let v = Int(o)
    let count = bb.read(def: Int32.self, position: v)
    self = bb.readString(
      at: MemoryLayout<Int32>.size + v,
      count: Int(count)) ?? ""
  }
}
extension String: ObjectAPIPacker {
  public static func pack(
    _ builder: inout FlatBufferBuilder,
    obj: inout String?) -> Offset
  {
    guard var obj = obj else { return Offset() }
    return pack(&builder, obj: &obj)
  }
  public static func pack(
    _ builder: inout FlatBufferBuilder,
    obj: inout String) -> Offset
  {
    builder.create(string: obj)
  }
  public mutating func unpack() -> String {
    self
  }
}
extension String: NativeObject {
  public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
    where T.T == Self
  {
    fatalError("serialize should never be called from string directly")
  }
  public func serialize<T: ObjectAPIPacker>(
    builder: inout FlatBufferBuilder,
    type: T.Type) -> ByteBuffer where T.T == Self
  {
    fatalError("serialize should never be called from string directly")
  }
}


Mutable

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


ByteBuffer

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// `ByteBuffer` is the interface that stores the data for a `Flatbuffers` object
/// it allows users to write and read data directly from memory thus the use of its
/// functions should be used
    init(count: Int, alignment: Int) {
      memory = UnsafeMutableRawPointer.allocate(
        byteCount: count,
        alignment: alignment)
      capacity = count
      unowned = false
    }
    func copy(from ptr: UnsafeRawPointer, count: Int) {
      assert(
        !unowned,
        "copy should NOT be called on a buffer that is built by assumingMemoryBound")
      memory.copyMemory(from: ptr, byteCount: count)
    }
    func reallocate(_ size: Int, writerSize: Int, alignment: Int) {
      let currentWritingIndex = capacity &- writerSize
      while capacity <= writerSize &+ size {
        capacity = capacity << 1
      }
      /// solution take from Apple-NIO
      capacity = capacity.convertToPowerofTwo
      let newData = UnsafeMutableRawPointer.allocate(
        byteCount: capacity,
        alignment: alignment)
      memset(newData, 0, capacity &- writerSize)
      memcpy(
        newData.advanced(by: capacity &- writerSize),
        memory.advanced(by: currentWritingIndex),
        writerSize)
      memory.deallocate()
      memory = newData
    }
  }
  /// The size of the elements written to the buffer + their paddings
  private var _writerSize: Int = 0
  /// Aliginment of the current  memory being written to the buffer
  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
  var writerIndex: Int { _storage.capacity &- _writerSize }
  /// Reader is the position of the current Writer Index (capacity - size)
  public var reader: Int { writerIndex }
  /// Current size of the buffer
  public var size: UOffset { UOffset(_writerSize) }
  /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason
  public var memory: UnsafeMutableRawPointer { _storage.memory }
  /// Current capacity for the buffer
  public var capacity: Int { _storage.capacity }
  /// Constructor that creates a Flatbuffer object from a UInt8
  /// - Parameter bytes: Array of UInt8
  public init(bytes: [UInt8]) {
    var b = bytes
    _storage = Storage(count: bytes.count, alignment: alignment)
    _writerSize = _storage.capacity
    b.withUnsafeMutableBytes { bufferPointer in
      self._storage.copy(from: bufferPointer.baseAddress!, count: bytes.count)
    }
  }
  #if !os(WASI)
  /// Constructor that creates a Flatbuffer from the Swift Data type object
  /// - Parameter data: Swift data Object
  public init(data: Data) {
    var b = data
    _storage = Storage(count: data.count, alignment: alignment)
    _writerSize = _storage.capacity
    b.withUnsafeMutableBytes { bufferPointer in
      self._storage.copy(from: bufferPointer.baseAddress!, count: data.count)
    }
  }
  #endif
  /// Constructor that creates a Flatbuffer instance with a size
  /// - Parameter size: Length of the buffer
  init(initialSize size: Int) {
    let size = size.convertToPowerofTwo
    _storage = Storage(count: size, alignment: alignment)
    _storage.initialize(for: size)
  }
  #if swift(>=5.0) && !os(WASI)
  /// Constructor that creates a Flatbuffer object from a ContiguousBytes
  /// - Parameters:
  ///   - contiguousBytes: Binary stripe to use as the buffer
  ///   - count: amount of readable bytes
  public init<Bytes: ContiguousBytes>(
    contiguousBytes: Bytes,
    count: Int)
  {
    _storage = Storage(count: count, alignment: alignment)
    _writerSize = _storage.capacity
    contiguousBytes.withUnsafeBytes { buf in
      _storage.copy(from: buf.baseAddress!, count: buf.count)
    }
  }
  #endif
  /// - Parameter assumingMemoryBound: The unsafe memory region
  /// - Parameter capacity: The size of the given memory region
  public init(
    assumingMemoryBound memory: UnsafeMutableRawPointer,
    capacity: Int)
  {
    _storage = Storage(memory: memory, capacity: capacity, unowned: true)
    _writerSize = capacity
  }
  /// Creates a copy of the buffer that's being built by calling sizedBuffer
  /// - Parameters:
  ///   - memory: Current memory of the buffer
  ///   - count: count of bytes
  init(memory: UnsafeMutableRawPointer, count: Int) {
    _storage = Storage(count: count, alignment: alignment)
    _storage.copy(from: memory, count: count)
    _writerSize = _storage.capacity
  }
  /// - Parameters:
  ///   - memory: Current memory of the buffer
  ///   - count: count of bytes
  ///   - removeBytes: Removes a number of bytes from the current size
  init(
    memory: UnsafeMutableRawPointer,
    count: Int,
    removing removeBytes: Int)
  {
    _storage = Storage(count: count, alignment: alignment)
    _storage.copy(from: memory, count: count)
    _writerSize = removeBytes
  }
  /// Fills the buffer with padding by adding to the writersize
  /// - Parameter padding: Amount of padding between two to be serialized objects
  mutating func push<T: Scalar>(elements: [T]) {
    let size = elements.count &* MemoryLayout<T>.size
    ensureSpace(size: size)
    elements.reversed().forEach { s in
      push(value: s, len: MemoryLayout.size(ofValue: s))
    }
  }
  /// Adds an object of type NativeStruct into the buffer
  /// - Parameters:
  ///   - value: Object  that will be written to the buffer
  ///   - size: size to subtract from the WriterIndex
  mutating func push<T: Scalar>(value: T, len: Int) {
    ensureSpace(size: len)
    var v = value
    memcpy(_storage.memory.advanced(by: writerIndex &- len), &v, len)
    _writerSize = _writerSize &+ len
  }
  /// Adds a string to the buffer using swift.utf8 object
  /// - Parameter str: String that will be added to the buffer
  /// - Parameter len: length of the string
  mutating func push(string str: String, len: Int) {
    ensureSpace(size: len)
    if str.utf8
      .withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) !=
      nil
    {
    } else {
      let utf8View = str.utf8
      for c in utf8View.reversed() {
        push(value: c, len: 1)
      }
    }
  }
  /// Writes a string to Bytebuffer using UTF8View
  /// - Parameters:
  ///   - bytes: Pointer to the view
  ///   - len: Size of string
  mutating func push(
    bytes: UnsafeBufferPointer<String.UTF8View.Element>,
    len: Int) -> Bool
  {
    memcpy(
      _storage.memory.advanced(by: writerIndex &- len),
      UnsafeRawPointer(bytes.baseAddress!),
      len)
    _writerSize = _writerSize &+ len
    return true
  }
  /// Write stores an object into the buffer directly or indirectly.
  ///
  /// Direct: ignores the capacity of buffer which would mean we are referring to the direct point in memory
  /// indirect: takes into respect the current capacity of the buffer (capacity - index), writing to the buffer from the end
  /// - Parameters:
  ///   - value: Value that needs to be written to the buffer
  ///   - index: index to write to
  ///   - direct: Should take into consideration the capacity of the buffer
  mutating func ensureSpace(size: Int) -> Int {
    if size &+ _writerSize > _storage.capacity {
      _storage.reallocate(size, writerSize: _writerSize, alignment: alignment)
    }
    assert(size < FlatBufferMaxSize, "Buffer can't grow beyond 2 Gigabytes")
    return size
  }
  /// pops the written VTable if it's already written into the buffer
  /// - Parameter size: size of the `VTable`
  mutating public func clearSize() {
    _writerSize = 0
  }
  /// Clears the current instance of the buffer, replacing it with new memory
  public func read<T>(def: T.Type, position: Int) -> T {
    _storage.memory.advanced(by: position).load(as: T.self)
  }
  /// Reads a slice from the memory assuming a type of T
  /// - Parameters:
  ///   - index: index of the object to be read from the buffer
  ///   - count: count of bytes in memory
  public func readSlice<T>(
    index: Int,
    count: Int) -> [T]
  {
    assert(
      index + count <= _storage.capacity,
      "Reading out of bounds is illegal")
    let start = _storage.memory.advanced(by: index)
      .assumingMemoryBound(to: T.self)
    let array = UnsafeBufferPointer(start: start, count: count)
    return Array(array)
  }
  #if !os(WASI)
  /// Reads a string from the buffer and encodes it to a swift string
  /// - Parameters:
  ///   - index: index of the string in the buffer
  ///   - count: length of the string
  ///   - type: Encoding of the string
  public func readString(
    at index: Int,
    count: Int,
    type: String.Encoding = .utf8) -> String?
  {
    assert(
      index + count <= _storage.capacity,
      "Reading out of bounds is illegal")
    let start = _storage.memory.advanced(by: index)
      .assumingMemoryBound(to: UInt8.self)
    let bufprt = UnsafeBufferPointer(start: start, count: count)
    return String(bytes: Array(bufprt), encoding: type)
  }
  #else
  /// Reads a string from the buffer and encodes it to a swift string
  /// - Parameters:
  ///   - index: index of the string in the buffer
  ///   - count: length of the string
  ///   - type: Encoding of the string
  public func readString(
    at index: Int,
    count: Int) -> String?
  {
    assert(
      index + count <= _storage.capacity,
      "Reading out of bounds is illegal")
    let start = _storage.memory.advanced(by: index)
      .assumingMemoryBound(to: UInt8.self)
    let bufprt = UnsafeBufferPointer(start: start, count: count)
    return String(cString: bufprt.baseAddress!)
  }
  #endif
  /// Creates a new Flatbuffer object that's duplicated from the current one
  /// - Parameter removeBytes: the amount of bytes to remove from the current Size
  public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer {
    assert(removeBytes > 0, "Can NOT remove negative bytes")
    assert(
      removeBytes < _storage.capacity,
      "Can NOT remove more bytes than the ones allocated")
    return ByteBuffer(
      memory: _storage.memory,
      count: _storage.capacity,
      removing: _writerSize &- removeBytes)
  }
  /// Returns the written bytes into the ``ByteBuffer``
  public var underlyingBytes: [UInt8] {
    let cp = capacity &- writerIndex
    let start = memory.advanced(by: writerIndex)
      .bindMemory(to: UInt8.self, capacity: cp)
    let ptr = UnsafeBufferPointer<UInt8>(start: start, count: cp)
    return Array(ptr)
  }
  /// SkipPrefix Skips the first 4 bytes in case one of the following
  /// functions are called `getPrefixedSizeCheckedRoot` & `getPrefixedSizeRoot`
  /// which allows us to skip the first 4 bytes instead of recreating the buffer
  mutating func skipPrefix() -> Int32 {
    _writerSize = _writerSize &- MemoryLayout<Int32>.size
    return read(def: Int32.self, position: 0)
  }
}
extension ByteBuffer: CustomDebugStringConvertible {
  public var debugDescription: String {
    """
    buffer located at: \(_storage.memory), with capacity of \(_storage.capacity)
    { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \(writerIndex) }
    """
  }
}


NativeObject

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// NativeObject is a protocol that all of the `Object-API` generated code should be
/// conforming to since it allows developers the ease of use to pack and unpack their
/// Flatbuffers objects
public protocol NativeObject {}
extension NativeObject {
  /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly th
  /// - Parameter type: Type of the Flatbuffer object
  /// - Returns: returns the encoded sized ByteBuffer
  public func serialize<T: ObjectAPIPacker>(type: T.Type) -> ByteBuffer
    where T.T == Self
  {
    var builder = FlatBufferBuilder(initialSize: 1024)
    return serialize(builder: &builder, type: type.self)
  }
  /// Serialize is a helper function that serailizes the data from the Object API to a bytebuffer directly.
  ///
  /// - Parameters:
  ///   - builder: A FlatBufferBuilder
  ///   - type: Type of the Flatbuffer object
  /// - Returns: returns the encoded sized ByteBuffer
  /// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`.
  ///  It can be considered less expensive in terms of memory allocation
  public func serialize<T: ObjectAPIPacker>(
    builder: inout FlatBufferBuilder,
    type: T.Type) -> ByteBuffer where T.T == Self
  {
    var s = self
    let root = type.pack(&builder, obj: &s)
    builder.finish(offset: root)
    return builder.sizedBuffer
  }
}


FlatbuffersErrors

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Collection of thrown from the Flatbuffer verifier
public enum FlatbuffersErrors: Error, Equatable {
  /// Thrown when verifying a file id that doesnt match buffer id
  case bufferIdDidntMatchPassedId
  /// Prefixed size doesnt match the current (readable) buffer size
  case prefixedSizeNotEqualToBufferSize
  /// Thrown when buffer is bigger than the allowed 2GiB
  case exceedsMaxSizeAllowed
  /// Thrown when there is an missaligned pointer at position
  /// of type
  case missAlignedPointer(position: Int, type: String)
  /// Thrown when trying to read a value that goes out of the
  /// current buffer bounds
  case outOfBounds(position: UInt, end: Int)
  /// Thrown when the signed offset is out of the bounds of the
  /// current buffer
  case signedOffsetOutOfBounds(offset: Int, position: Int)
  /// Thrown when a required field doesnt exist within the buffer
  case requiredFieldDoesntExist(position: VOffset, name: String)
  /// Thrown when a string is missing its NULL Terminator `\0`,
  /// this can be disabled in the `VerifierOptions`
  case missingNullTerminator(position: Int, str: String?)
  /// Thrown when the verifier has reached the maximum tables allowed,
  /// this can be disabled in the `VerifierOptions`
  case maximumTables
  /// Thrown when the verifier has reached the maximum depth allowed,
  /// this can be disabled in the `VerifierOptions`
  case maximumDepth
  /// Thrown when the verifier is presented with an unknown union case
  case unknownUnionCase
  /// thrown when a value for a union is not found within the buffer
  case valueNotFound(key: Int?, keyName: String, field: Int?, fieldName: String)
  /// thrown when the size of the keys vector doesnt match fields vector
  case unionVectorSize(
    keyVectorSize: Int,
    fieldVectorSize: Int,
    unionKeyName: String,
    fieldName: String)
  case apparentSizeTooLarge
}
#if !os(WASI)
extension FlatbuffersErrors {
  public static func == (
    lhs: FlatbuffersErrors,
    rhs: FlatbuffersErrors) -> Bool
  {
    lhs.localizedDescription == rhs.localizedDescription
  }
}
#endif


Enum

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Enum is a protocol that all flatbuffers enums should conform to
/// Since it allows us to get the actual `ByteSize` and `Value` from
/// a swift enum.
public protocol Enum {
  /// associatedtype that the type of the enum should conform to
  associatedtype T: Scalar & Verifiable
  /// Size of the current associatedtype in the enum
  static var byteSize: Int { get }
  /// The current value the enum hosts
  var value: T { get }
}
extension Enum where Self: Verifiable {
  /// Verifies that the current value is which the bounds of the buffer, and if
  /// the current `Value` is aligned properly
  /// - Parameters:
  ///   - verifier: Verifier that hosts the buffer
  ///   - position: Current position within the buffer
  ///   - type: The type of the object to be verified
  /// - Throws: Errors coming from `inBuffer` function
  public static func verify<T>(
    _ verifier: inout Verifier,
    at position: Int,
    of type: T.Type) throws where T: Verifiable
  {
    try verifier.inBuffer(position: position, of: type.self)
  }
}
/// UnionEnum is a Protocol that allows us to create Union type of enums
/// and their value initializers. Since an `init` was required by
/// the verifier
public protocol UnionEnum: Enum {
  init?(value: T) throws
}


Int+extension

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


Root

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Takes in a prefixed sized buffer, where the prefixed size would be skipped.
/// And would verify that the buffer passed is a valid `Flatbuffers` Object.
/// - Parameters:
///   - byteBuffer: Buffer that needs to be checked and read
///   - options: Verifier options
/// - Throws: FlatbuffersErrors
/// - Returns: Returns a valid, checked Flatbuffers object
///
/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in
/// the ``ByteBuffer`` and verifies the buffer by calling ``getCheckedRoot(byteBuffer:options:)``
public func getPrefixedSizeCheckedRoot<T: FlatBufferObject & Verifiable>(
  byteBuffer: inout ByteBuffer,
  fileId: String? = nil,
  options: VerifierOptions = .init()) throws -> T
{
  byteBuffer.skipPrefix()
  return try getCheckedRoot(
    byteBuffer: &byteBuffer,
    fileId: fileId,
    options: options)
}
/// Takes in a prefixed sized buffer, where we check if the sized buffer is equal to prefix size.
/// And would verify that the buffer passed is a valid `Flatbuffers` Object.
/// - Parameters:
///   - byteBuffer: Buffer that needs to be checked and read
///   - options: Verifier options
/// - Throws: FlatbuffersErrors
/// - Returns: Returns a valid, checked Flatbuffers object
///
/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in
/// the ``ByteBuffer`` and verifies the buffer by calling ``getCheckedRoot(byteBuffer:options:)``
public func getCheckedPrefixedSizeRoot<T: FlatBufferObject & Verifiable>(
  byteBuffer: inout ByteBuffer,
  fileId: String? = nil,
  options: VerifierOptions = .init()) throws -> T
{
  let prefix = byteBuffer.skipPrefix()
  if prefix != byteBuffer.size {
    throw FlatbuffersErrors.prefixedSizeNotEqualToBufferSize
  }
  return try getCheckedRoot(
    byteBuffer: &byteBuffer,
    fileId: fileId,
    options: options)
}
/// Takes in a prefixed sized buffer, where the prefixed size would be skipped.
/// Returns a `NON-Checked` flatbuffers object
/// - Parameter byteBuffer: Buffer that contains data
/// - Returns: Returns a Flatbuffers object
///
/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in
/// the ``ByteBuffer`` and then calls ``getRoot(byteBuffer:)``
public func getPrefixedSizeRoot<T: FlatBufferObject>(byteBuffer: inout ByteBuffer)
  -> T
{
  byteBuffer.skipPrefix()
  return getRoot(byteBuffer: &byteBuffer)
}
/// Verifies that the buffer passed is a valid `Flatbuffers` Object.
/// - Parameters:
///   - byteBuffer: Buffer that needs to be checked and read
///   - options: Verifier options
/// - Throws: FlatbuffersErrors
/// - Returns: Returns a valid, checked Flatbuffers object
///
/// ``getCheckedRoot(byteBuffer:options:)`` Takes in a ``ByteBuffer`` and verifies
/// that by creating a ``Verifier`` and checkes if all the `Bytes` and correctly aligned
/// and within the ``ByteBuffer`` range.
public func getCheckedRoot<T: FlatBufferObject & Verifiable>(
  byteBuffer: inout ByteBuffer,
  fileId: String? = nil,
  options: VerifierOptions = .init()) throws -> T
{
  var verifier = try Verifier(buffer: &byteBuffer, options: options)
  if let fileId = fileId {
    try verifier.verify(id: fileId)
  }
  try ForwardOffset<T>.verify(&verifier, at: 0, of: T.self)
  return T.init(
    byteBuffer,
    o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) +
      Int32(byteBuffer.reader))
}
/// Returns a `NON-Checked` flatbuffers object
/// - Parameter byteBuffer: Buffer that contains data
/// - Returns: Returns a Flatbuffers object
public func getRoot<T: FlatBufferObject>(byteBuffer: inout ByteBuffer) -> T {
  T.init(
    byteBuffer,
    o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) +
      Int32(byteBuffer.reader))
}


Offset

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Offset object for all the Objects that are written into the buffer
public struct Offset {
  /// Offset of the object in the buffer
  public var o: UOffset
  /// Returns false if the offset is equal to zero
  public var isEmpty: Bool { o == 0 }
  public init(offset: UOffset) { o = offset }
  public init() { o = 0 }
}