FlatBufferBuilder

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// ``FlatBufferBuilder`` builds a `FlatBuffer` through manipulating its internal state.
///
/// This is done by creating a ``ByteBuffer`` that hosts the incoming data and
/// has a hardcoded growth limit of `2GiB` which is set by the Flatbuffers standards.
///
/// ```swift
/// var builder = FlatBufferBuilder()
/// ```
/// The builder should be always created as a variable, since it would be passed into the writers
///
  /// Reference Vtables that were already written to the buffer
  private var _vtables: [UOffset] = []
  /// A check if the buffer is being written into by a different table
  private var isNested = false
  /// Dictonary that stores a map of all the strings that were written to the buffer
  private var stringOffsetMap: [String: Offset] = [:]
  /// A check to see if finish(::) was ever called to retreive data object
  private var finished = false
  /// A check to see if the buffer should serialize Default values
  private var serializeDefaults: Bool
  /// Current alignment for the buffer
  var _minAlignment: Int = 0 {
    didSet {
      _bb.alignment = _minAlignment
    }
  }
  /// Gives a read access to the buffer's size
  public var size: UOffset { _bb.size }
  #if !os(WASI)
  /// Data representation of the buffer
  ///
  /// Should only be used after ``finish(offset:addPrefix:)`` is called
  public var data: Data {
    assert(finished, "Data shouldn't be called before finish()")
    return Data(
      bytes: _bb.memory.advanced(by: _bb.writerIndex),
      count: _bb.capacity &- _bb.writerIndex)
  }
  #endif
  /// Returns the underlying bytes in the ``ByteBuffer``
  ///
  /// Note: This should be used with caution.
  public var fullSizedByteArray: [UInt8] {
    let ptr = UnsafeBufferPointer(
      start: _bb.memory.assumingMemoryBound(to: UInt8.self),
      count: _bb.capacity)
    return Array(ptr)
  }
  /// Returns the written bytes into the ``ByteBuffer``
  ///
  /// Should only be used after ``finish(offset:addPrefix:)`` is called
  public var sizedByteArray: [UInt8] {
    assert(finished, "Data shouldn't be called before finish()")
    return _bb.underlyingBytes
  }
  /// Returns the original ``ByteBuffer``
  ///
  /// Returns the current buffer that was just created
  /// with the offsets, and data written to it.
  public var buffer: ByteBuffer { _bb }
  /// Returns a newly created sized ``ByteBuffer``
  ///
  /// returns a new buffer that is sized to the data written
  /// to the main buffer
  public var sizedBuffer: ByteBuffer {
    assert(finished, "Data shouldn't be called before finish()")
    return ByteBuffer(
      memory: _bb.memory.advanced(by: _bb.reader),
      count: Int(_bb.size))
  }
  // MARK: - Init
  /// Initialize the buffer with a size
  /// - Parameters:
  ///   - initialSize: Initial size for the buffer
  ///   - force: Allows default to be serialized into the buffer
  ///
  /// This initializes a new builder with an initialSize that would initialize
  /// a new ``ByteBuffer``. ``FlatBufferBuilder`` by default doesnt serialize defaults
  /// however the builder can be force by passing true for `serializeDefaults`
  public init(
    initialSize: Int32 = 1024,
    serializeDefaults force: Bool = false)
  {
    assert(initialSize > 0, "Size should be greater than zero!")
    guard isLitteEndian else {
      fatalError(
        "Reading/Writing a buffer in big endian machine is not supported on swift")
    }
    serializeDefaults = force
    _bb = ByteBuffer(initialSize: Int(initialSize))
  }
  /// Clears the builder and the buffer from the written data.
  mutating public func clear() {
    _minAlignment = 0
    isNested = false
    stringOffsetMap.removeAll(keepingCapacity: true)
    _vtables.removeAll(keepingCapacity: true)
    _vtableStorage.clear()
    _bb.clear()
  }
  // MARK: - Create Tables
  /// Checks if the required fields were serialized into the buffer
  /// - Parameters:
  ///   - table: offset for the table
  ///   - fields: Array of all the important fields to be serialized
  ///
  /// *NOTE: Never call this function, this is only supposed to be called
  /// by the generated code*
  mutating public func require(table: Offset, fields: [Int32]) {
    for field in fields {
      let start = _bb.capacity &- Int(table.o)
      let startTable = start &- Int(_bb.read(def: Int32.self, position: start))
      let isOkay = _bb.read(
        def: VOffset.self,
        position: startTable &+ Int(field)) != 0
      assert(isOkay, "Flatbuffers requires the following field")
    }
  }
  /// Finished the buffer by adding the file id and then calling finish
  /// - Parameters:
  ///   - offset: Offset of the table
  ///   - fileId: Takes the fileId
  ///   - prefix: if false it wont add the size of the buffer
  ///
  /// ``finish(offset:fileId:addPrefix:)`` should be called at the end of creating
  /// a table
  /// ```swift
  /// var root = SomeObject
  ///   .createObject(&builder,
  ///   name: nameOffset)
  /// builder.finish(
  ///   offset: root,
  ///   fileId: "ax1a",
  ///   addPrefix: true)
  /// ```
  /// File id would append a file id name at the end of the written bytes before,
  /// finishing the buffer.
  ///
  /// Whereas, if `addPrefix` is true, the written bytes would
  /// include the size of the current buffer.
  mutating public func finish(
    offset: Offset,
    fileId: String,
    addPrefix prefix: Bool = false)
  {
    let size = MemoryLayout<UOffset>.size
    preAlign(
      len: size &+ (prefix ? size : 0) &+ FileIdLength,
      alignment: _minAlignment)
    assert(fileId.count == FileIdLength, "Flatbuffers requires file id to be 4")
    _bb.push(string: fileId, len: 4)
    finish(offset: offset, addPrefix: prefix)
  }
  /// Finished the buffer by adding the file id, offset, and prefix to it.
  /// - Parameters:
  ///   - offset: Offset of the table
  ///   - prefix: if false it wont add the size of the buffer
  ///
  /// ``finish(offset:addPrefix:)`` should be called at the end of creating
  /// a table
  /// ```swift
  /// var root = SomeObject
  ///   .createObject(&builder,
  ///   name: nameOffset)
  /// builder.finish(
  ///   offset: root,
  ///   addPrefix: true)
  /// ```
  /// If `addPrefix` is true, the written bytes would
  /// include the size of the current buffer.
  mutating public func finish(
    offset: Offset,
    addPrefix prefix: Bool = false)
  {
    notNested()
    let size = MemoryLayout<UOffset>.size
    preAlign(len: size &+ (prefix ? size : 0), alignment: _minAlignment)
    push(element: refer(to: offset.o))
    if prefix { push(element: _bb.size) }
    _vtableStorage.clear()
    finished = true
  }
  /// ``startTable(with:)`` will let the builder know, that a new object is being serialized.
  ///
  /// The function will fatalerror if called while there is another object being serialized.
  /// ```swift
  /// let start = Monster
  ///   .startMonster(&fbb)
  /// ```
  /// - Parameter numOfFields: Number of elements to be written to the buffer
  /// - Returns: Offset of the newly started table
  mutating public func startTable(with numOfFields: Int) -> UOffset {
    notNested()
    isNested = true
    _vtableStorage.start(count: numOfFields)
    return _bb.size
  }
  /// ``endTable(at:)`` will let the ``FlatBufferBuilder`` know that the
  /// object that's written to it is completed
  ///
  /// This would be called after all the elements are serialized,
  /// it will add the current vtable into the ``ByteBuffer``.
  /// The functions will `fatalError` in case the object is called
  /// without ``startTable(with:)``, or the object has exceeded  the limit of 2GB.
  ///
  /// - Parameter startOffset:Start point of the object written
  /// - returns: The root of the table
  mutating public func endTable(at startOffset: UOffset)  -> UOffset {
    assert(isNested, "Calling endtable without calling starttable")
    let sizeofVoffset = MemoryLayout<VOffset>.size
    let vTableOffset = push(element: SOffset(0))
    let tableObjectSize = vTableOffset &- startOffset
    assert(tableObjectSize < 0x10000, "Buffer can't grow beyond 2 Gigabytes")
    let _max = Int(_vtableStorage.maxOffset) &+ sizeofVoffset
    _bb.fill(padding: _max)
    _bb.write(
      value: VOffset(tableObjectSize),
      index: _bb.writerIndex &+ sizeofVoffset,
      direct: true)
    _bb.write(value: VOffset(_max), index: _bb.writerIndex, direct: true)
    var itr = 0
    while itr < _vtableStorage.writtenIndex {
      let loaded = _vtableStorage.load(at: itr)
      itr = itr &+ _vtableStorage.size
      guard loaded.offset != 0 else { continue }
      let _index = (_bb.writerIndex &+ Int(loaded.position))
      _bb.write(
        value: VOffset(vTableOffset &- loaded.offset),
        index: _index,
        direct: true)
    }
    _vtableStorage.clear()
    let vt_use = _bb.size
    var isAlreadyAdded: Int?
    let vt2 = _bb.memory.advanced(by: _bb.writerIndex)
    let len2 = vt2.load(fromByteOffset: 0, as: Int16.self)
    for table in _vtables {
      let position = _bb.capacity &- Int(table)
      let vt1 = _bb.memory.advanced(by: position)
      let len1 = _bb.read(def: Int16.self, position: position)
      if len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2)) { continue }
      isAlreadyAdded = Int(table)
      break
    }
    if let offset = isAlreadyAdded {
      let vTableOff = Int(vTableOffset)
      let space = _bb.capacity &- vTableOff
      _bb.write(value: Int32(offset &- vTableOff), index: space, direct: true)
      _bb.pop(_bb.capacity &- space)
    } else {
      _bb.write(value: Int32(vt_use &- vTableOffset), index: Int(vTableOffset))
      _vtables.append(_bb.size)
    }
    isNested = false
    return vTableOffset
  }
  // MARK: - Builds Buffer
  /// Asserts to see if the object is not nested
  mutating internal func minAlignment(size: Int) {
    if size > _minAlignment {
      _minAlignment = size
    }
  }
  /// Gets the padding for the current element
  /// - Parameters:
  ///   - bufSize: Current size of the buffer + the offset of the object to be written
  ///   - elementSize: Element size
  mutating internal func preAlign(len: Int, alignment: Int) {
    minAlignment(size: alignment)
    _bb.fill(padding: Int(padding(
      bufSize: _bb.size &+ UOffset(len),
      elementSize: UOffset(alignment))))
  }
  /// Prealigns the buffer before writting a new object into the buffer
  /// - Parameters:
  ///   - len: Length of the object
  ///   - type: Type of the object to be written
  mutating internal func refer(to off: UOffset) -> UOffset {
    let size = MemoryLayout<UOffset>.size
    preAlign(len: size, alignment: size)
    return _bb.size &- off &+ UInt32(size)
  }
  /// Tracks the elements written into the buffer
  /// - Parameters:
  ///   - offset: The offset of the element witten
  ///   - position: The position of the element
  mutating internal func track(offset: UOffset, at position: VOffset) {
    _vtableStorage.add(loc: FieldLoc(offset: offset, position: position))
  }
  // MARK: - Inserting Vectors
  /// ``startVector(_:elementSize:)`` creates a new vector within buffer
  ///
  /// The function checks if there is a current object being written, if
  /// the check passes it creates a buffer alignment of `length * elementSize`
  /// ```swift
  /// builder.startVector(
  ///   int32Values.count, elementSize: 4)
  /// ```
  ///
  /// - Parameters:
  ///   - len: Length of vector to be created
  ///   - elementSize: Size of object type to be written
  mutating public func startVector(_ len: Int, elementSize: Int) {
    notNested()
    isNested = true
    preAlign(len: len &* elementSize, type: UOffset.self)
    preAlign(len: len &* elementSize, alignment: elementSize)
  }
  /// ``endVector(len:)`` ends the currently created vector
  ///
  /// Calling ``endVector(len:)`` requires the length, of the current
  /// vector. The length would be pushed to indicate the count of numbers
  /// within the vector. If ``endVector(len:)`` is called without
  /// ``startVector(_:elementSize:)`` it asserts.
  ///
  /// ```swift
  /// let vectorOffset = builder.
  ///   endVector(len: int32Values.count)
  /// ```
  ///
  /// - Parameter len: Length of the buffer
  /// - Returns: Returns the current ``Offset`` in the ``ByteBuffer``
  mutating public func endVector(len: Int) -> Offset {
    assert(isNested, "Calling endVector without calling startVector")
    isNested = false
    return Offset(offset: push(element: Int32(len)))
  }
  /// Creates a vector of type ``Scalar`` into the ``ByteBuffer``
  ///
  /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into
  /// ``ByteBuffer``. This is a convenient method instead of calling,
  /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
  /// ```swift
  /// let vectorOffset = builder.
  ///   createVector([1, 2, 3, 4])
  /// ```
  ///
  /// The underlying implementation simply calls ``createVector(_:size:)-4lhrv``
  ///
  /// - Parameter elements: elements to be written into the buffer
  /// - returns: ``Offset`` of the vector
  mutating public func createVector<T: Scalar>(_ elements: [T]) -> Offset {
    createVector(elements, size: elements.count)
  }
  ///  Creates a vector of type Scalar in the buffer
  ///
  /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into
  /// ``ByteBuffer``. This is a convenient method instead of calling,
  /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
  /// ```swift
  /// let vectorOffset = builder.
  ///   createVector([1, 2, 3, 4], size: 4)
  /// ```
  ///
  /// - Parameter elements: Elements to be written into the buffer
  /// - Parameter size: Count of elements
  /// - returns: ``Offset`` of the vector
  mutating public func createVector<T: Scalar>(
    _ elements: [T],
    size: Int) -> Offset
  {
    let size = size
    startVector(size, elementSize: MemoryLayout<T>.size)
    _bb.push(elements: elements)
    return endVector(len: size)
  }
  /// Creates a vector of type ``Enum`` into the ``ByteBuffer``
  ///
  /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into
  /// ``ByteBuffer``. This is a convenient method instead of calling,
  /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
  /// ```swift
  /// let vectorOffset = builder.
  ///   createVector([.swift, .cpp])
  /// ```
  ///
  /// The underlying implementation simply calls ``createVector(_:size:)-7cx6z``
  ///
  /// - Parameter elements: elements to be written into the buffer
  /// - returns: ``Offset`` of the vector
  mutating public func createVector<T: Enum>(_ elements: [T]) -> Offset {
    createVector(elements, size: elements.count)
  }
  /// Creates a vector of type ``Enum`` into the ``ByteBuffer``
  ///
  /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into
  /// ``ByteBuffer``. This is a convenient method instead of calling,
  /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
  /// ```swift
  /// let vectorOffset = builder.
  ///   createVector([.swift, .cpp])
  /// ```
  ///
  /// - Parameter elements: Elements to be written into the buffer
  /// - Parameter size: Count of elements
  /// - returns: ``Offset`` of the vector
  mutating public func createVector<T: Enum>(
    _ elements: [T],
    size: Int) -> Offset
  {
    let size = size
    startVector(size, elementSize: T.byteSize)
    for e in elements.reversed() {
      _bb.push(value: e.value, len: T.byteSize)
    }
    return endVector(len: size)
  }
  /// Creates a vector of already written offsets
  ///
  /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into
  /// ``ByteBuffer``. This is a convenient method instead of calling,
  /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``.
  ///
  /// The underlying implementation simply calls ``createVector(ofOffsets:len:)``
  ///
  /// ```swift
  /// let namesOffsets = builder.
  ///   createVector(ofOffsets: [name1, name2])
  /// ```
  /// - Parameter offsets: Array of offsets of type ``Offset``
  /// - returns: ``Offset`` of the vector
  mutating public func createVector(ofOffsets offsets: [Offset]) -> Offset {
    createVector(ofOffsets: offsets, len: offsets.count)
  }
  /// Creates a vector of already written offsets
  ///
  /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into
  /// ``ByteBuffer``. This is a convenient method instead of calling,
  /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``
  ///
  /// ```swift
  /// let namesOffsets = builder.
  ///   createVector(ofOffsets: [name1, name2])
  /// ```
  ///
  /// - Parameter offsets: Array of offsets of type ``Offset``
  /// - Parameter size: Count of elements
  /// - returns: ``Offset`` of the vector
  mutating public func createVector(
    ofOffsets offsets: [Offset],
    len: Int) -> Offset
  {
    startVector(len, elementSize: MemoryLayout<Offset>.size)
    for o in offsets.reversed() {
      push(element: o)
    }
    return endVector(len: len)
  }
  /// Creates a vector of strings
  ///
  /// ``createVector(ofStrings:)`` creates a vector of `String` into
  /// ``ByteBuffer``. This is a convenient method instead of manually
  /// creating the string offsets, you simply pass it to this function
  /// and it would write the strings into the ``ByteBuffer``.
  /// After that it calls ``createVector(ofOffsets:)``
  ///
  /// ```swift
  /// let namesOffsets = builder.
  ///   createVector(ofStrings: ["Name", "surname"])
  /// ```
  ///
  /// - Parameter str: Array of string
  /// - returns: ``Offset`` of the vector
  mutating public func createVector(ofStrings str: [String]) -> Offset {
    var offsets: [Offset] = []
    for s in str {
      offsets.append(create(string: s))
    }
    return createVector(ofOffsets: offsets)
  }
  /// Creates a vector of type ``NativeStruct``.
  ///
  /// Any swift struct in the generated code, should confirm to
  /// ``NativeStruct``. Since the generated swift structs are padded
  /// to the `FlatBuffers` standards.
  ///
  /// ```swift
  /// let offsets = builder.
  ///   createVector(ofStructs: [NativeStr(num: 1), NativeStr(num: 2)])
  /// ```
  ///
  /// - Parameter structs: A vector of ``NativeStruct``
  /// - Returns: ``Offset`` of the vector
  mutating public func createVector<T: NativeStruct>(ofStructs structs: [T])
    -> Offset
  {
    startVector(
      structs.count * MemoryLayout<T>.size,
      elementSize: MemoryLayout<T>.alignment)
    for i in structs.reversed() {
      _ = create(struct: i)
    }
    return endVector(len: structs.count)
  }
  // MARK: - Inserting Structs
  /// Writes a ``NativeStruct`` into the ``ByteBuffer``
  ///
  /// Adds a native struct that's build and padded according
  /// to `FlatBuffers` standards. with a predefined position.
  ///
  /// ```swift
  /// let offset = builder.create(
  ///   struct: NativeStr(num: 1),
  ///   position: 10)
  /// ```
  ///
  /// - Parameters:
  ///   - s: ``NativeStruct`` to be inserted into the ``ByteBuffer``
  ///   - position: The  predefined position of the object
  /// - Returns: ``Offset`` of written struct
  mutating public func create<T: NativeStruct>(
    struct s: T, position: VOffset) -> Offset
  {
    let offset = create(struct: s)
    _vtableStorage.add(loc: FieldLoc(
      offset: _bb.size,
      position: VOffset(position)))
    return offset
  }
  /// Writes a ``NativeStruct`` into the ``ByteBuffer``
  ///
  /// Adds a native struct that's build and padded according
  /// to `FlatBuffers` standards, directly into the buffer without
  /// a predefined position.
  ///
  /// ```swift
  /// let offset = builder.create(
  ///   struct: NativeStr(num: 1))
  /// ```
  ///
  /// - Parameters:
  ///   - s: ``NativeStruct`` to be inserted into the ``ByteBuffer``
  /// - Returns: ``Offset`` of written struct
  mutating public func create<T: NativeStruct>(
    struct s: T) -> Offset
  {
    let size = MemoryLayout<T>.size
    preAlign(len: size, alignment: MemoryLayout<T>.alignment)
    _bb.push(struct: s, size: size)
    return Offset(offset: _bb.size)
  }
  // MARK: - Inserting Strings
  /// Insets a string into the buffer of type `UTF8`
  ///
  /// Adds a swift string into ``ByteBuffer`` by encoding it
  /// using `UTF8`
  ///
  /// ```swift
  /// let nameOffset = builder
  ///   .create(string: "welcome")
  /// ```
  ///
  /// - Parameter str: String to be serialized
  /// - returns: ``Offset`` of inserted string
  mutating public func create(string str: String?) -> Offset {
    guard let str = str else { return Offset() }
    let len = str.utf8.count
    notNested()
    preAlign(len: len &+ 1, type: UOffset.self)
    _bb.fill(padding: 1)
    _bb.push(string: str, len: len)
    push(element: UOffset(len))
    return Offset(offset: _bb.size)
  }
  /// Insets a shared string into the buffer of type `UTF8`
  ///
  /// Adds a swift string into ``ByteBuffer`` by encoding it
  /// using `UTF8`. The function will check if the string,
  /// is already written to the ``ByteBuffer``
  ///
  /// ```swift
  /// let nameOffset = builder
  ///   .createShared(string: "welcome")
  ///
  ///
  /// let secondOffset = builder
  ///   .createShared(string: "welcome")
  ///
  /// assert(nameOffset.o == secondOffset.o)
  /// ```
  ///
  /// - Parameter str: String to be serialized
  /// - returns: ``Offset`` of inserted string
  mutating public func createShared(string str: String?) -> Offset {
    guard let str = str else { return Offset() }
    if let offset = stringOffsetMap[str] {
      return offset
    }
    let offset = create(string: str)
    stringOffsetMap[str] = offset
    return offset
  }
  // MARK: - Inseting offsets
  /// Writes the ``Offset`` of an already written table
  ///
  /// Writes the ``Offset`` of a table if not empty into the
  /// ``ByteBuffer``
  ///
  /// - Parameters:
  ///   - offset: ``Offset`` of another object to be written
  ///   - position: The predefined position of the object
  mutating public func push(element o: Offset) -> UOffset {
    push(element: refer(to: o.o))
  }
  // MARK: - Inserting Scalars to Buffer
  /// Writes a ``Scalar`` value into ``ByteBuffer``
  ///
  /// ``add(element:def:at:)`` takes in a default value, and current value
  /// and the position within the `VTable`. The default value would not
  /// be serialized if the value is the same as the current value or
  /// `serializeDefaults` is equal to false.
  ///
  /// If serializing defaults is important ``init(initialSize:serializeDefaults:)``,
  /// passing true for `serializeDefaults` would do the job.
  ///
  /// ```swift
  /// // Adds 10 to the buffer
  /// builder.add(element: Int(10), def: 1, position 12)
  /// ```
  ///
  /// *NOTE: Never call this manually*
  ///
  /// - Parameters:
  ///   - element: Element to insert
  ///   - def: Default value for that element
  ///   - position: The predefined position of the element
  mutating public func add<T: Scalar>(
    element: T,
    def: T,
    at position: VOffset)
  {
    if element == def && !serializeDefaults { return }
    track(offset: push(element: element), at: position)
  }
  /// Writes a optional ``Scalar`` value into ``ByteBuffer``
  ///
  /// Takes an optional value to be written into the ``ByteBuffer``
  ///
  /// *NOTE: Never call this manually*
  ///
  /// - Parameters:
  ///   - element: Optional element of type scalar
  ///   - position: The predefined position of the element
  mutating public func push<T: Scalar>(element: T) -> UOffset {
    let size = MemoryLayout<T>.size
    preAlign(
      len: size,
      alignment: size)
    _bb.push(value: element, len: size)
    return _bb.size
  }
}
extension FlatBufferBuilder: CustomDebugStringConvertible {
  public var debugDescription: String {
    """
    buffer debug:
    \(_bb)
    builder debug:
    { finished: \(finished), serializeDefaults: \(serializeDefaults), isNested: \(isNested) }
    """
  }
  /// VTableStorage is a class to contain the VTable buffer that would be serialized into buffer
  internal class VTableStorage {
    /// Memory check since deallocating each time we want to clear would be expensive
    /// and memory leaks would happen if we dont deallocate the first allocated memory.
    /// memory is promised to be available before adding `FieldLoc`
    private var memoryInUse = false
    /// Size of FieldLoc in memory
    let size = MemoryLayout<FieldLoc>.stride
    /// Memeory buffer
    var memory: UnsafeMutableRawBufferPointer!
    /// Capacity of the current buffer
    var capacity: Int = 0
    /// Maximuim offset written to the class
    var maxOffset: VOffset = 0
    /// number of fields written into the buffer
    var numOfFields: Int = 0
    /// Last written Index
    var writtenIndex: Int = 0
    /// Creates the memory to store the buffer in
    func start(count: Int) {
      assert(count >= 0, "number of fields should NOT be negative")
      let capacity = count &* size
      ensure(space: capacity)
    }
    /// Adds a FieldLoc into the buffer, which would track how many have been written,
    /// and max offset
    /// - Parameter loc: Location of encoded element
    func clear() {
      maxOffset = 0
      numOfFields = 0
      writtenIndex = 0
    }
    /// Ensure that the buffer has enough space instead of recreating the buffer each time.
    /// - Parameter space: space required for the new vtable
    func load(at index: Int) -> FieldLoc {
      memory.load(fromByteOffset: index, as: FieldLoc.self)
    }
  }
  internal struct FieldLoc {
    var offset: UOffset
    var position: VOffset
  }
}


Struct

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Struct is a representation of a mutable `Flatbuffers` struct
/// since native structs are value types and cant be mutated
public struct Struct {
  /// Hosting Bytebuffer
  public private(set) var bb: ByteBuffer
  /// Current position of the struct
  public private(set) var postion: Int32
  /// Initializer for a mutable flatbuffers struct
  /// - Parameters:
  ///   - bb: Current hosting Bytebuffer
  ///   - position: Current position for the struct in the ByteBuffer
  public init(bb: ByteBuffer, position: Int32 = 0) {
    self.bb = bb
    postion = position
  }
  /// Reads data from the buffer directly at offset O
  /// - Parameters:
  ///   - type: Type of data to be read
  ///   - o: Current offset of the data
  /// - Returns: Data of Type T that conforms to type Scalar
  public func readBuffer<T: Scalar>(of type: T.Type, at o: Int32) -> T {
    let r = bb.read(def: T.self, position: Int(o + postion))
    return r
  }
}


Verifiable

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Verifiable is a protocol all swift flatbuffers object should conform to,
/// since swift is similar to `cpp` and `rust` where the data is read directly
/// from `unsafeMemory` thus the need to verify if the buffer received is a valid one
public protocol 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
  static func verify<T>(
    _ verifier: inout Verifier,
    at position: Int,
    of type: T.Type) throws where T: Verifiable
}
extension Verifiable {
  /// Verifies if the current range to be read is within the bounds of the buffer,
  /// and if the range is properly aligned
  /// - Parameters:
  ///   - verifier: Verifier that hosts the buffer
  ///   - position: Current position within the buffer
  ///   - type: The type of the object to be verified
  /// - Throws: Erros thrown from `isAligned` & `rangeInBuffer`
  /// - Returns: a tuple of the start position and the count of objects within the range
  public static func verifyRange<T>(
    _ verifier: inout Verifier,
    at position: Int, of type: T.Type) throws -> (start: Int, count: Int)
  {
    let len: UOffset = try verifier.getValue(at: position)
    let intLen = Int(len)
    let start = Int(clamping: (position &+ MemoryLayout<Int32>.size).magnitude)
    try verifier.isAligned(position: start, type: type.self)
    try verifier.rangeInBuffer(position: start, size: intLen)
    return (start, intLen)
  }
}
extension Verifiable where Self: Scalar {
  /// 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)
  }
}
// MARK: - ForwardOffset
/// ForwardOffset is a container to wrap around the Generic type to be verified
/// from the flatbuffers object.
public enum ForwardOffset<U>: Verifiable where U: 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
  {
    let offset: UOffset = try verifier.getValue(at: position)
    let nextOffset = Int(clamping: (Int(offset) &+ position).magnitude)
    try U.verify(&verifier, at: nextOffset, of: U.self)
  }
}
// MARK: - Vector
/// Vector is a container to wrap around the Generic type to be verified
/// from the flatbuffers object.
public enum Vector<U, S>: Verifiable where U: Verifiable, S: 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
  {
    /// checks if the next verification type S is equal to U of type forwardOffset
    /// This had to be done since I couldnt find a solution for duplicate call functions
    /// A fix will be appreciated
    if U.self is ForwardOffset<S>.Type {
      let range = try verifyRange(&verifier, at: position, of: UOffset.self)
      for index in stride(
        from: range.start,
        to: Int(clamping: range.start &+ range.count),
        by: MemoryLayout<UOffset>.size)
      {
        try U.verify(&verifier, at: index, of: U.self)
      }
    } else {
      try S.verifyRange(&verifier, at: position, of: S.self)
    }
  }
}
// MARK: - UnionVector
/// UnionVector is a container to wrap around the Generic type to be verified
/// from the flatbuffers object.
public enum UnionVector<S> where S: UnionEnum {
  /// Completion handler for the function Verify, that passes the verifier
  /// enum type and position of union field
  public typealias Completion = (inout Verifier, S, Int) throws -> Void
  /// Verifies if the current range to be read is within the bounds of the buffer,
  /// and if the range is properly aligned. It also verifies if the union type is a
  /// *valid/supported* union type.
  /// - Parameters:
  ///   - verifier: Verifier that hosts the buffer
  ///   - keyPosition: Current union key position within the buffer
  ///   - fieldPosition: Current union field position within the buffer
  ///   - unionKeyName: Name of key to written if error is presented
  ///   - fieldName: Name of field to written if error is presented
  ///   - completion: Completion is a handler that WILL be called in the generated
  ///   code to verify the actual objects
  /// - Throws: FlatbuffersErrors
  public static func verify(
    _ verifier: inout Verifier,
    keyPosition: Int,
    fieldPosition: Int,
    unionKeyName: String,
    fieldName: String,
  {
    /// Get offset for union key vectors and offset vectors
    let keyOffset: UOffset = try verifier.getValue(at: keyPosition)
    let fieldOffset: UOffset = try verifier.getValue(at: fieldPosition)
    /// Check if values are within the buffer, returns the start position of vectors, and vector counts
    /// Using &+ is safe since we already verified that the value is within the buffer, where the max is
    /// going to be 2Gib and swift supports Int64 by default
    let keysRange = try S.T.verifyRange(
      &verifier,
      at: Int(keyOffset) &+ keyPosition,
      of: S.T.self)
    let offsetsRange = try UOffset.verifyRange(
      &verifier,
      at: Int(fieldOffset) &+ fieldPosition,
      of: UOffset.self)
    guard keysRange.count == offsetsRange.count else {
      throw FlatbuffersErrors.unionVectorSize(
        keyVectorSize: keysRange.count,
        fieldVectorSize: offsetsRange.count,
        unionKeyName: unionKeyName,
        fieldName: fieldName)
    }
    var count = 0
    /// Iterate over the vector of keys and offsets.
    while count < keysRange.count {
      /// index of readable enum value in array
      let keysIndex = MemoryLayout<S.T>.size * count
      guard let _enum = try S.init(value: verifier._buffer.read(
        def: S.T.self,
        position: keysRange.start + keysIndex)) else
      {
        throw FlatbuffersErrors.unknownUnionCase
      }
      /// index of readable offset value in array
      let fieldIndex = MemoryLayout<UOffset>.size * count
      try completion(&verifier, _enum, offsetsRange.start + fieldIndex)
      count += 1
    }
  }
}


Verifier

/*
 */
#if !os(WASI)
import Foundation
#else
import SwiftOverlayShims
#endif
/// Verifier that check if the buffer passed into it is a valid,
/// safe, aligned Flatbuffers object since swift read from `unsafeMemory`
public struct Verifier {
  /// Flag to check for alignment if true
  fileprivate let _checkAlignment: Bool
  /// Capacity of the current buffer
  fileprivate var _capacity: Int
  /// Current ApparentSize
  fileprivate var _apparentSize: UOffset = 0
  /// Amount of tables present within a buffer
  fileprivate var _tableCount = 0
  /// Capacity of the buffer
  internal var capacity: Int { _capacity }
  /// Current reached depth within the buffer
  internal var _depth = 0
  /// Current verifiable ByteBuffer
  internal var _buffer: ByteBuffer
  /// Options for verification
  internal let _options: VerifierOptions
  /// Initializer for the verifier
  /// - Parameters:
  ///   - buffer: Bytebuffer that is required to be verified
  ///   - options: `VerifierOptions` that set the rule for some of the verification done
  ///   - checkAlignment: If alignment check is required to be preformed
  /// - Throws: `exceedsMaxSizeAllowed` if capacity of the buffer is more than 2GiB
  public init(
    buffer: inout ByteBuffer,
    options: VerifierOptions = .init(),
    checkAlignment: Bool = true) throws
  {
    guard buffer.capacity < FlatBufferMaxSize else {
      throw FlatbuffersErrors.exceedsMaxSizeAllowed
    }
    _buffer = buffer
    _capacity = buffer.capacity
    _checkAlignment = checkAlignment
    _options = options
  }
  /// Resets the verifier to initial state
  public mutating func reset() {
    _depth = 0
    _tableCount = 0
  }
  /// Checks if the value of type `T` is aligned properly in the buffer
  /// - Parameters:
  ///   - position: Current position
  ///   - type: Type of value to check
  /// - Throws: `missAlignedPointer` if the pointer is not aligned properly
  public mutating func isAligned<T>(position: Int, type: T.Type) throws {
    /// If check alignment is false this mutating function doesnt continue
    if !_checkAlignment { return }
    /// advance pointer to position X
    let ptr = _buffer._storage.memory.advanced(by: position)
    /// Check if the pointer is aligned
    if Int(bitPattern: ptr) & (MemoryLayout<T>.alignment &- 1) == 0 {
      return
    }
    throw FlatbuffersErrors.missAlignedPointer(
      position: position,
      type: String(describing: T.self))
  }
  /// Checks if the value of Size "X" is within the range of the buffer
  /// - Parameters:
  ///   - position: Current postion to be read
  ///   - size: `Byte` Size of readable object within the buffer
  /// - Throws: `outOfBounds` if the value is out of the bounds of the buffer
  /// and `apparentSizeTooLarge` if the apparent size is bigger than the one specified
  /// in `VerifierOptions`
  public mutating func rangeInBuffer(position: Int, size: Int) throws {
    let end = UInt(clamping: (position &+ size).magnitude)
    if end > _buffer.capacity {
      throw FlatbuffersErrors.outOfBounds(position: end, end: capacity)
    }
    _apparentSize = _apparentSize &+ UInt32(size)
    if _apparentSize > _options._maxApparentSize {
      throw FlatbuffersErrors.apparentSizeTooLarge
    }
  }
  /// Validates if a value of type `T` is aligned and within the bounds of
  /// the buffer
  /// - Parameters:
  ///   - position: Current readable position
  ///   - type: Type of value to check
  /// - Throws: FlatbuffersErrors
  public mutating func inBuffer<T>(position: Int, of type: T.Type) throws {
    try isAligned(position: position, type: type)
    try rangeInBuffer(position: position, size: MemoryLayout<T>.size)
  }
  /// Visits a table at the current position and validates if the table meets
  /// the rules specified in the `VerifierOptions`
  /// - Parameter position: Current position to be read
  /// - Throws: FlatbuffersErrors
  /// - Returns: A `TableVerifier` at the current readable table
  public mutating func visitTable(at position: Int) throws -> TableVerifier {
    let vtablePosition = try derefOffset(position: position)
    let vtableLength: VOffset = try getValue(at: vtablePosition)
    let length = Int(vtableLength)
    try isAligned(
      position: Int(clamping: (vtablePosition + length).magnitude),
      type: VOffset.self)
    try rangeInBuffer(position: vtablePosition, size: length)
    _tableCount += 1
    if _tableCount > _options._maxTableCount {
      throw FlatbuffersErrors.maximumTables
    }
    _depth += 1
    if _depth > _options._maxDepth {
      throw FlatbuffersErrors.maximumDepth
    }
    return TableVerifier(
      position: position,
      vtable: vtablePosition,
      vtableLength: length,
      verifier: &self)
  }
  /// Validates if a value of type `T` is within the buffer and returns it
  /// - Parameter position: Current position to be read
  /// - Throws: `inBuffer` errors
  /// - Returns: a value of type `T` usually a `VTable` or a table offset
  internal mutating func getValue<T>(at position: Int) throws -> T {
    try inBuffer(position: position, of: T.self)
    return _buffer.read(def: T.self, position: position)
  }
  /// derefrences an offset within a vtable to get the position of the field
  /// in the bytebuffer
  /// - Parameter position: Current readable position
  /// - Throws: `inBuffer` errors & `signedOffsetOutOfBounds`
  /// - Returns: Current readable position for a field
  internal mutating func derefOffset(position: Int) throws -> Int {
    try inBuffer(position: position, of: Int32.self)
    let offset = _buffer.read(def: Int32.self, position: position)
    // switching to int32 since swift's default Int is int64
    // this should be safe since we already checked if its within
    // the buffer
    let _int32Position = UInt32(position)
    let reportedOverflow: (partialValue: UInt32, overflow: Bool)
    if offset > 0 {
      reportedOverflow = _int32Position
        .subtractingReportingOverflow(offset.magnitude)
    } else {
      reportedOverflow = _int32Position
        .addingReportingOverflow(offset.magnitude)
    }
    /// since `subtractingReportingOverflow` & `addingReportingOverflow` returns true,
    /// if there is overflow we return failure
    if reportedOverflow.overflow || reportedOverflow.partialValue > _buffer
      .capacity
    {
      throw FlatbuffersErrors.signedOffsetOutOfBounds(
        offset: Int(offset),
        position: position)
    }
    return Int(reportedOverflow.partialValue)
  }
  /// finishes the current iteration of verification on an object
  internal mutating func finish() {
    _depth -= 1
  }
  mutating func verify(id: String) throws {
    let size = MemoryLayout<Int32>.size
    let str = _buffer.readString(at: size, count: size)
    if id == str {
      return
    }
    throw FlatbuffersErrors.bufferIdDidntMatchPassedId
  }
}


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
  var byteBuffer = ByteBuffer(bytes: buf)
  // Get an accessor to the root object inside the buffer.
  let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer)
  // let monster: Monster = getRoot(byteBuffer: &byteBuffer)
}


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 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 `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 ByteBuffer(:) from an [UInt8] or Data()
  let buf = [] // Get your data
  var byteBuffer = ByteBuffer(bytes: buf)
  // Get an accessor to the root object inside the buffer.
  let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer)
  // let monster: Monster = getRoot(byteBuffer: &byteBuffer)

  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)

  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


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
  var byteBuffer = ByteBuffer(bytes: buf)
  // Get an accessor to the root object inside the buffer.
  let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer)
  // let monster: Monster = getRoot(byteBuffer: &byteBuffer)

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


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

import FlatBuffers

public struct Galaxy: 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 numStars = 4
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }

  public var numStars: Int64 { let o = _accessor.offset(VTOFFSET.numStars.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) }
  public static func startGalaxy(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
  public static func add(numStars: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numStars, def: 0, at: VTOFFSET.numStars.p) }
  public static func endGalaxy(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createGalaxy(
    _ fbb: inout FlatBufferBuilder,
    numStars: Int64 = 0
  ) -> Offset {
    let __start = Galaxy.startGalaxy(&fbb)
    Galaxy.add(numStars: numStars, &fbb)
    return Galaxy.endGalaxy(&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.numStars.p, fieldName: "numStars", required: false, type: Int64.self)
    _v.finish()
  }
}

public struct Universe: 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 age = 4
    case galaxies = 6
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }

  public var age: Double { let o = _accessor.offset(VTOFFSET.age.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) }
  public var hasGalaxies: Bool { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? false : true }
  public var galaxiesCount: Int32 { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? 0 : _accessor.vector(count: o) }
  public func galaxies(at index: Int32) -> Galaxy? { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? nil : Galaxy(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
  public static func startUniverse(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) }
  public static func add(age: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: age, def: 0.0, at: VTOFFSET.age.p) }
  public static func addVectorOf(galaxies: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: galaxies, at: VTOFFSET.galaxies.p) }
  public static func endUniverse(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createUniverse(
    _ fbb: inout FlatBufferBuilder,
    age: Double = 0.0,
    galaxiesVectorOffset galaxies: Offset = Offset()
  ) -> Offset {
    let __start = Universe.startUniverse(&fbb)
    Universe.add(age: age, &fbb)
    Universe.addVectorOf(galaxies: galaxies, &fbb)
    return Universe.endUniverse(&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.age.p, fieldName: "age", required: false, type: Double.self)
    try _v.visit(field: VTOFFSET.galaxies.p, fieldName: "galaxies", required: false, type: ForwardOffset<Vector<ForwardOffset<Galaxy>, Galaxy>>.self)
    _v.finish()
  }
}


Package

// swift-tools-version:5.1
/*
 */
import PackageDescription
let package = Package(
  name: "benchmarks",
  platforms: [
    .macOS(.v10_14),
  ],
  dependencies: [
    .package(path: "../../.."),
    .package(url: "https://github.com/google/swift-benchmark", from: "0.1.0"),
  ],
  targets: [
    .target(
      name: "benchmarks",
      dependencies: ["FlatBuffers",
                     .product(name: "Benchmark", package: "swift-benchmark")]),
  ])


main

/*
 */
import Benchmark
import CoreFoundation
import FlatBuffers
benchmark("10Strings") {
  var fb = FlatBufferBuilder(initialSize: 1<<20)
  for _ in 0..<1_000_000 {
    _ = fb.create(string: "foobarbaz")
  }
}
benchmark("100Strings") {
  var fb = FlatBufferBuilder(initialSize: 1<<20)
  for _ in 0..<1_000_000 {
    _ = fb.create(string: str)
  }
}
benchmark("FlatBufferBuilder.add") {
  var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32)
  for _ in 0..<1_000_000 {
    let off = fb.create(string: "T")
    let s = fb.startTable(with: 4)
    fb.add(element: 3.2, def: 0, at: 2)
    fb.add(element: 4.2, def: 0, at: 4)
    fb.add(element: 5.2, def: 0, at: 6)
    fb.add(offset: off, at: 8)
    _ = fb.endTable(at: s)
  }
}
benchmark("structs") {
  let structCount = 1_000_000
  let rawSize = ((16 * 5) * structCount) / 1024
  var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600))
  var offsets: [Offset] = []
  for _ in 0..<structCount {
    fb.startVector(
      5 * MemoryLayout<AA>.size,
      elementSize: MemoryLayout<AA>.alignment)
    for _ in 0..<5 {
      _ = fb.create(struct: AA(a: 2.4, b: 2.4))
    }
    let vector = fb.endVector(len: 5)
    let start = fb.startTable(with: 1)
    fb.add(offset: vector, at: 4)
    offsets.append(Offset(offset: fb.endTable(at: start)))
  }
  let vector = fb.createVector(ofOffsets: offsets)
  let start = fb.startTable(with: 1)
  fb.add(offset: vector, at: 4)
  let root = Offset(offset: fb.endTable(at: start))
  fb.finish(offset: root)
}
let str = (0...99).map { _ -> String in "x" }.joined()
struct AA: NativeStruct {
  public init(a: Double, b: Double) {
    self.a = a
    self.b = b
  }
  var a: Double
  var b: Double
}
Benchmark.main()


Package

// swift-tools-version:5.1
/*
 */
import PackageDescription
let package = Package(
  name: "FlatBuffers.Test.Swift",
  platforms: [
    .iOS(.v11),
    .macOS(.v10_14),
  ],
  dependencies: [
    .package(path: "../../.."),
    .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1"),
  ],
  targets: [
    .target(
      name: "SwiftFlatBuffers",
      dependencies: ["FlatBuffers"]),
    .testTarget(
      name: "FlatBuffers.Test.SwiftTests",
      dependencies: ["FlatBuffers", "GRPC"]),
  ])


// automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
// swiftformat:disable all
internal struct Message: FlatBufferObject, Verifiable, ObjectAPIPacker {
  static func validateVersion() { FlatBuffersVersion_23_5_9() }
  internal var __buffer: ByteBuffer! { return _accessor.bb }
  private var _accessor: Table
  private init(_ t: Table) { _accessor = t }
  internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
  private enum VTOFFSET: VOffset {
    case internalMessage = 4
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }
  internal var internalMessage: String? { let o = _accessor.offset(VTOFFSET.internalMessage.v); return o == 0 ? nil : _accessor.string(at: o) }
  internal var internalMessageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.internalMessage.v) }
  internal static func startMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
  internal static func add(internalMessage: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: internalMessage, at: VTOFFSET.internalMessage.p) }
  internal static func endMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  internal static func createMessage(
    _ fbb: inout FlatBufferBuilder,
    internalMessageOffset internalMessage: Offset = Offset()
  ) -> Offset {
    let __start = Message.startMessage(&fbb)
    Message.add(internalMessage: internalMessage, &fbb)
    return Message.endMessage(&fbb, start: __start)
  }

  internal mutating func unpack() -> MessageT {
    return MessageT(&self)
  }
  internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT?) -> Offset {
    guard var obj = obj else { return Offset() }
    return pack(&builder, obj: &obj)
  }
  internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT) -> Offset {
    let __internalMessage: Offset
    if let s = obj.internalMessage {
      __internalMessage = builder.create(string: s)
    } else {
      __internalMessage = Offset()
    }
    let __root = Message.startMessage(&builder)
    Message.add(internalMessage: __internalMessage, &builder)
    return Message.endMessage(&builder, start: __root)
  }
  internal 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.internalMessage.p, fieldName: "internalMessage", required: false, type: ForwardOffset<String>.self)
    _v.finish()
  }
}
extension Message: Encodable {
  enum CodingKeys: String, CodingKey {
    case internalMessage = "internal_message"
  }
  internal func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encodeIfPresent(internalMessage, forKey: .internalMessage)
  }
}
internal class MessageT: NativeObject {
  internal var internalMessage: String?
  internal init(_ _t: inout Message) {
    internalMessage = _t.internalMessage
  }
  internal init() {
  }
  internal func serialize() -> ByteBuffer { return serialize(type: Message.self) }
}


// automatically generated by the FlatBuffers compiler, do not modify
// swiftlint:disable all
// swiftformat:disable all
public struct BytesCount: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject {
  static func validateVersion() { FlatBuffersVersion_23_5_9() }
  private var _x: Int64
  public init(_ bb: ByteBuffer, o: Int32) {
    let _accessor = Struct(bb: bb, position: o)
    _x = _accessor.readBuffer(of: Int64.self, at: 0)
  }
  public init(x: Int64) {
    _x = x
  }
  public init() {
    _x = 0
  }
  public init(_ _t: inout BytesCount_Mutable) {
    _x = _t.x
  }
  public var x: Int64 { _x }
  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: BytesCount.self)
  }
}
extension BytesCount: Encodable {
  enum CodingKeys: String, CodingKey {
    case x = "x"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    if x != 0 {
      try container.encodeIfPresent(x, forKey: .x)
    }
  }
}
public struct BytesCount_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: Int64 { return _accessor.readBuffer(of: Int64.self, at: 0) }

  public mutating func unpack() -> BytesCount {
    return BytesCount(&self)
  }
  public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BytesCount?) -> Offset {
    guard var obj = obj else { return Offset() }
    return pack(&builder, obj: &obj)
  }
  public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BytesCount) -> Offset {
    return builder.create(struct: obj)
  }
}
public struct InternalMessage: FlatBufferObject, Verifiable, ObjectAPIPacker {
  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 str = 4
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }
  public var str: String? { let o = _accessor.offset(VTOFFSET.str.v); return o == 0 ? nil : _accessor.string(at: o) }
  public var strSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.str.v) }
  public static func startInternalMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
  public static func add(str: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: str, at: VTOFFSET.str.p) }
  public static func endInternalMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end }
  public static func createInternalMessage(
    _ fbb: inout FlatBufferBuilder,
    strOffset str: Offset = Offset()
  ) -> Offset {
    let __start = InternalMessage.startInternalMessage(&fbb)
    InternalMessage.add(str: str, &fbb)
    return InternalMessage.endInternalMessage(&fbb, start: __start)
  }

  public mutating func unpack() -> InternalMessageT {
    return InternalMessageT(&self)
  }
  public static func pack(_ builder: inout FlatBufferBuilder, obj: inout InternalMessageT?) -> Offset {
    guard var obj = obj else { return Offset() }
    return pack(&builder, obj: &obj)
  }
  public static func pack(_ builder: inout FlatBufferBuilder, obj: inout InternalMessageT) -> Offset {
    let __str: Offset
    if let s = obj.str {
      __str = builder.create(string: s)
    } else {
      __str = Offset()
    }
    let __root = InternalMessage.startInternalMessage(&builder)
    InternalMessage.add(str: __str, &builder)
    return InternalMessage.endInternalMessage(&builder, start: __root)
  }
  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.str.p, fieldName: "str", required: false, type: ForwardOffset<String>.self)
    _v.finish()
  }
}
extension InternalMessage: Encodable {
  enum CodingKeys: String, CodingKey {
    case str = "str"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encodeIfPresent(str, forKey: .str)
  }
}
public class InternalMessageT: NativeObject {
  public var str: String?
  public init(_ _t: inout InternalMessage) {
    str = _t.str
  }
  public init() {
  }
  public func serialize() -> ByteBuffer { return serialize(type: InternalMessage.self) }
}
public struct Message: FlatBufferObject, Verifiable, ObjectAPIPacker {
  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 id = 4
    case position = 6
    case pointer = 8
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }
  public var id: Int64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) }
  public var position: BytesCount! { let o = _accessor.offset(VTOFFSET.position.v); return _accessor.readBuffer(of: BytesCount.self, at: o) }
  public var mutablePosition: BytesCount_Mutable! { let o = _accessor.offset(VTOFFSET.position.v); return BytesCount_Mutable(_accessor.bb, o: o + _accessor.postion) }
  public var pointer: InternalMessage! { let o = _accessor.offset(VTOFFSET.pointer.v); return InternalMessage(_accessor.bb, o: _accessor.indirect(o + _accessor.postion)) }
  public static func startMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) }
  public static func add(id: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) }
  public static func add(position: BytesCount?, _ fbb: inout FlatBufferBuilder) { guard let position = position else { return }; fbb.create(struct: position, position: VTOFFSET.position.p) }
  public static func add(pointer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: pointer, at: VTOFFSET.pointer.p) }
  public static func endMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [6, 8]); return end }
  public static func createMessage(
    _ fbb: inout FlatBufferBuilder,
    id: Int64 = 0,
    position: BytesCount,
    pointerOffset pointer: Offset
  ) -> Offset {
    let __start = Message.startMessage(&fbb)
    Message.add(id: id, &fbb)
    Message.add(position: position, &fbb)
    Message.add(pointer: pointer, &fbb)
    return Message.endMessage(&fbb, start: __start)
  }

  public mutating func unpack() -> MessageT {
    return MessageT(&self)
  }
  public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT?) -> Offset {
    guard var obj = obj else { return Offset() }
    return pack(&builder, obj: &obj)
  }
  public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT) -> Offset {
    let __pointer = InternalMessage.pack(&builder, obj: &obj.pointer)
    let __root = Message.startMessage(&builder)
    Message.add(id: obj.id, &builder)
    Message.add(position: obj.position, &builder)
    Message.add(pointer: __pointer, &builder)
    return Message.endMessage(&builder, start: __root)
  }
  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.id.p, fieldName: "id", required: false, type: Int64.self)
    try _v.visit(field: VTOFFSET.position.p, fieldName: "position", required: true, type: BytesCount.self)
    try _v.visit(field: VTOFFSET.pointer.p, fieldName: "pointer", required: true, type: ForwardOffset<InternalMessage>.self)
    _v.finish()
  }
}
extension Message: Encodable {
  enum CodingKeys: String, CodingKey {
    case id = "id"
    case position = "position"
    case pointer = "pointer"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    if id != 0 {
      try container.encodeIfPresent(id, forKey: .id)
    }
    try container.encodeIfPresent(position, forKey: .position)
    try container.encodeIfPresent(pointer, forKey: .pointer)
  }
}
public class MessageT: NativeObject {
  public var id: Int64
  public var position: BytesCount
  public var pointer: InternalMessageT
  public init(_ _t: inout Message) {
    id = _t.id
    position = _t.position
    var __pointer = _t.pointer
    pointer = __pointer!.unpack()
  }
  public init() {
    id = 0
    position = BytesCount()
    pointer = InternalMessageT()
  }
  public func serialize() -> ByteBuffer { return serialize(type: Message.self) }
}


main

/*
public func FuzzFlatbuffers(_ start: UnsafeRawPointer, _ count: Int) -> CInt {
  let bytes = UnsafeRawBufferPointer(start: start, count: count)
  do {
    var buffer = ByteBuffer(contiguousBytes: bytes, count: count)
    let _: Monster = try getCheckedRoot(byteBuffer: &buffer)
  } catch {
  }
  return 0
}


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

import FlatBuffers

public enum Color: UInt8, Enum, Verifiable {
  public typealias T = UInt8
  public static var byteSize: Int { return MemoryLayout<UInt8>.size }
  public var value: UInt8 { return self.rawValue }
  case red = 1
  ///  \brief color Green
  ///  Green is bit_flag with value (1u << 1)
  case green = 2
  ///  \brief color Blue (1u << 3)
  case blue = 8

  public static var max: Color { return .blue }
  public static var min: Color { return .red }
}

extension Color: Encodable {
  public func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()
    switch self {
    case .red: try container.encode("Red")
    case .green: try container.encode("Green")
    case .blue: try container.encode("Blue")
    }
  }
}

public struct Test: NativeStruct, Verifiable, FlatbuffersInitializable {

  static func validateVersion() { FlatBuffersVersion_23_5_9() }

  private var _a: Int16
  private var _b: Int8
  private let padding0__: UInt8 = 0

  public init(_ bb: ByteBuffer, o: Int32) {
    let _accessor = Struct(bb: bb, position: o)
    _a = _accessor.readBuffer(of: Int16.self, at: 0)
    _b = _accessor.readBuffer(of: Int8.self, at: 2)
  }

  public init(a: Int16, b: Int8) {
    _a = a
    _b = b
  }

  public init() {
    _a = 0
    _b = 0
  }

  public var a: Int16 { _a }
  public var b: Int8 { _b }

  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: Test.self)
  }
}

extension Test: Encodable {

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

public struct Test_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 a: Int16 { return _accessor.readBuffer(of: Int16.self, at: 0) }
  public var b: Int8 { return _accessor.readBuffer(of: Int8.self, at: 2) }
}

public struct Vec3: NativeStruct, Verifiable, FlatbuffersInitializable {

  static func validateVersion() { FlatBuffersVersion_23_5_9() }

  private var _x: Float32
  private var _y: Float32
  private var _z: Float32
  private let padding0__: UInt32 = 0
  private var _test1: Double
  private var _test2: UInt8
  private let padding1__: UInt8 = 0
  private var _test3: Test
  private let padding2__: UInt16 = 0

  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)
    _test1 = _accessor.readBuffer(of: Double.self, at: 16)
    _test2 = _accessor.readBuffer(of: UInt8.self, at: 24)
    _test3 = Test(_accessor.bb, o: _accessor.postion + 26)
  }

  public init(x: Float32, y: Float32, z: Float32, test1: Double, test2: Color, test3: Test) {
    _x = x
    _y = y
    _z = z
    _test1 = test1
    _test2 = test2.value
    _test3 = test3
  }

  public init() {
    _x = 0.0
    _y = 0.0
    _z = 0.0
    _test1 = 0.0
    _test2 = 0
    _test3 = Test()
  }

  public var x: Float32 { _x }
  public var y: Float32 { _y }
  public var z: Float32 { _z }
  public var test1: Double { _test1 }
  public var test2: Color { Color(rawValue: _test2)! }
  public var test3: Test { _test3 }

  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: Vec3.self)
  }
}

extension Vec3: Encodable {

  enum CodingKeys: String, CodingKey {
    case x = "x"
    case y = "y"
    case z = "z"
    case test1 = "test1"
    case test2 = "test2"
    case test3 = "test3"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    if x != 0.0 {
      try container.encodeIfPresent(x, forKey: .x)
    }
    if y != 0.0 {
      try container.encodeIfPresent(y, forKey: .y)
    }
    if z != 0.0 {
      try container.encodeIfPresent(z, forKey: .z)
    }
    if test1 != 0.0 {
      try container.encodeIfPresent(test1, forKey: .test1)
    }
    if test2 != .red {
      try container.encodeIfPresent(test2, forKey: .test2)
    }
    try container.encodeIfPresent(test3, forKey: .test3)
  }
}

public struct 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 var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) }
  public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) }
  public var test1: Double { return _accessor.readBuffer(of: Double.self, at: 16) }
  public var test2: Color { return Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: 24)) ?? .red }
  public var test3: Test_Mutable { return Test_Mutable(_accessor.bb, o: _accessor.postion + 26) }
}

///  an example documentation comment: "monster object"
public struct Monster: FlatBufferObject, Verifiable {

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

  public static func getRootAsMonster(bb: ByteBuffer) -> Monster { return Monster(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 pos = 4
    case mana = 6
    case hp = 8
    case name = 10
    case testarrayoftables = 12
    case inventory = 14
    case color = 16
    var v: Int32 { Int32(self.rawValue) }
    var p: VOffset { self.rawValue }
  }

  public var pos: Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: Vec3.self, at: o) }
  public var mutablePos: Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : 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 hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) }
  public var name: String! { let o = _accessor.offset(VTOFFSET.name.v); return _accessor.string(at: o) }
  public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) }
  public var hasTestarrayoftables: Bool { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? false : true }
  public var testarrayoftablesCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? 0 : _accessor.vector(count: o) }
  public func testarrayoftables(at index: Int32) -> Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : Monster(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) }
  public func testarrayoftablesBy(key: String) -> Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) }
  public var hasInventory: Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? false : true }
  public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) }
  public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) }
  public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] }
  public var color: Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue }
  public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 7) }
  public static func add(pos: 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(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) }
  public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) }
  public static func add(color: Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) }
  public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end }
  public static func createMonster(
    _ fbb: inout FlatBufferBuilder,
    pos: Vec3? = nil,
    mana: Int16 = 150,
    hp: Int16 = 100,
    nameOffset name: Offset,
    testarrayoftablesVectorOffset testarrayoftables: Offset = Offset(),
    inventoryVectorOffset inventory: Offset = Offset(),
    color: Color = .blue
  ) -> Offset {
    let __start = Monster.startMonster(&fbb)
    Monster.add(pos: pos, &fbb)
    Monster.add(mana: mana, &fbb)
    Monster.add(hp: hp, &fbb)
    Monster.add(name: name, &fbb)
    Monster.addVectorOf(testarrayoftables: testarrayoftables, &fbb)
    Monster.addVectorOf(inventory: inventory, &fbb)
    Monster.add(color: color, &fbb)
    return Monster.endMonster(&fbb, start: __start)
  }
  public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset {
    var off = offsets
    off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 }
    return fbb.createVector(ofOffsets: off)
  }
  fileprivate static func lookupByKey(vector: Int32, key: String, fbb: ByteBuffer) -> Monster? {
    let key = key.utf8.map { $0 }
    var span = fbb.read(def: Int32.self, position: Int(vector - 4))
    var start: Int32 = 0
    while span != 0 {
      var middle = span / 2
      let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb)
      let comp = Table.compare(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 10, fbb: fbb), key, fbb: fbb)
      if comp > 0 {
        span = middle
      } else if comp < 0 {
        middle += 1
        start += middle
        span -= middle
      } else {
        return Monster(fbb, o: tableOffset)
      }
    }
    return nil
  }

  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: 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: true, type: ForwardOffset<String>.self)
    try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset<Vector<ForwardOffset<Monster>, Monster>>.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: Color.self)
    _v.finish()
  }
}

extension Monster: Encodable {

  enum CodingKeys: String, CodingKey {
    case pos = "pos"
    case mana = "mana"
    case hp = "hp"
    case name = "name"
    case testarrayoftables = "testarrayoftables"
    case inventory = "inventory"
    case color = "color"
  }
  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encodeIfPresent(pos, forKey: .pos)
    if mana != 150 {
      try container.encodeIfPresent(mana, forKey: .mana)
    }
    if hp != 100 {
      try container.encodeIfPresent(hp, forKey: .hp)
    }
    try container.encodeIfPresent(name, forKey: .name)
    if testarrayoftablesCount > 0 {
      var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayoftables)
      for index in 0..<testarrayoftablesCount {
        guard let type = testarrayoftables(at: index) else { continue }
        try contentEncoder.encode(type)
      }
    }
    if inventoryCount > 0 {
      try container.encodeIfPresent(inventory, forKey: .inventory)
    }
    if color != .blue {
      try container.encodeIfPresent(color, forKey: .color)
    }
  }
}


LinuxMain

/*
 */
import XCTest
import FlatBuffers_Test_SwiftTests
var tests = [XCTestCaseEntry]()
tests += FlatBuffers_Test_SwiftTests.__allTests()
XCTMain(tests)