// This file was autogenerated by some hot garbage in the `uniffi` crate.
// Trust me, you don't want to mess with it!

// swiftlint:disable all
import Foundation

// Depending on the consumer's build setup, the low-level FFI code
// might be in a separate module, or it might be compiled inline into
// this module. This is a bit of light hackery to work with both.
#if canImport(peat_apple_ffiFFI)
import peat_apple_ffiFFI
#endif

fileprivate extension RustBuffer {
    // Allocate a new buffer, copying the contents of a `UInt8` array.
    init(bytes: [UInt8]) {
        let rbuf = bytes.withUnsafeBufferPointer { ptr in
            RustBuffer.from(ptr)
        }
        self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
    }

    static func empty() -> RustBuffer {
        RustBuffer(capacity: 0, len:0, data: nil)
    }

    static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
        try! rustCall { ffi_peat_apple_ffi_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
    }

    // Frees the buffer in place.
    // The buffer must not be used after this is called.
    func deallocate() {
        try! rustCall { ffi_peat_apple_ffi_rustbuffer_free(self, $0) }
    }
}

fileprivate extension ForeignBytes {
    init(bufferPointer: UnsafeBufferPointer<UInt8>) {
        self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
    }
}

// For every type used in the interface, we provide helper methods for conveniently
// lifting and lowering that type from C-compatible data, and for reading and writing
// values of that type in a buffer.

// Helper classes/extensions that don't change.
// Someday, this will be in a library of its own.

fileprivate extension Data {
    init(rustBuffer: RustBuffer) {
        self.init(
            bytesNoCopy: rustBuffer.data!,
            count: Int(rustBuffer.len),
            deallocator: .none
        )
    }
}

// Define reader functionality.  Normally this would be defined in a class or
// struct, but we use standalone functions instead in order to make external
// types work.
//
// With external types, one swift source file needs to be able to call the read
// method on another source file's FfiConverter, but then what visibility
// should Reader have?
// - If Reader is fileprivate, then this means the read() must also
//   be fileprivate, which doesn't work with external types.
// - If Reader is internal/public, we'll get compile errors since both source
//   files will try define the same type.
//
// Instead, the read() method and these helper functions input a tuple of data

fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
    (data: data, offset: 0)
}

// Reads an integer at the current offset, in big-endian order, and advances
// the offset on success. Throws if reading the integer would move the
// offset past the end of the buffer.
fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
    let range = reader.offset..<reader.offset + MemoryLayout<T>.size
    guard reader.data.count >= range.upperBound else {
        throw UniffiInternalError.bufferOverflow
    }
    if T.self == UInt8.self {
        let value = reader.data[reader.offset]
        reader.offset += 1
        return value as! T
    }
    var value: T = 0
    let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
    reader.offset = range.upperBound
    return value.bigEndian
}

// Reads an arbitrary number of bytes, to be used to read
// raw bytes, this is useful when lifting strings
fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
    let range = reader.offset..<(reader.offset+count)
    guard reader.data.count >= range.upperBound else {
        throw UniffiInternalError.bufferOverflow
    }
    var value = [UInt8](repeating: 0, count: count)
    value.withUnsafeMutableBufferPointer({ buffer in
        reader.data.copyBytes(to: buffer, from: range)
    })
    reader.offset = range.upperBound
    return value
}

// Reads a float at the current offset.
fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
    return Float(bitPattern: try readInt(&reader))
}

// Reads a float at the current offset.
fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
    return Double(bitPattern: try readInt(&reader))
}

// Indicates if the offset has reached the end of the buffer.
fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
    return reader.offset < reader.data.count
}

// Define writer functionality.  Normally this would be defined in a class or
// struct, but we use standalone functions instead in order to make external
// types work.  See the above discussion on Readers for details.

fileprivate func createWriter() -> [UInt8] {
    return []
}

fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
    writer.append(contentsOf: byteArr)
}

// Writes an integer in big-endian order.
//
// Warning: make sure what you are trying to write
// is in the correct type!
fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
    var value = value.bigEndian
    withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
}

fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
    writeInt(&writer, value.bitPattern)
}

fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
    writeInt(&writer, value.bitPattern)
}

// Protocol for types that transfer other types across the FFI. This is
// analogous to the Rust trait of the same name.
fileprivate protocol FfiConverter {
    associatedtype FfiType
    associatedtype SwiftType

    static func lift(_ value: FfiType) throws -> SwiftType
    static func lower(_ value: SwiftType) -> FfiType
    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
    static func write(_ value: SwiftType, into buf: inout [UInt8])
}

// Types conforming to `Primitive` pass themselves directly over the FFI.
fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }

extension FfiConverterPrimitive {
#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lift(_ value: FfiType) throws -> SwiftType {
        return value
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lower(_ value: SwiftType) -> FfiType {
        return value
    }
}

// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
// Used for complex types where it's hard to write a custom lift/lower.
fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}

extension FfiConverterRustBuffer {
#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lift(_ buf: RustBuffer) throws -> SwiftType {
        var reader = createReader(data: Data(rustBuffer: buf))
        let value = try read(from: &reader)
        if hasRemaining(reader) {
            throw UniffiInternalError.incompleteData
        }
        buf.deallocate()
        return value
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lower(_ value: SwiftType) -> RustBuffer {
          var writer = createWriter()
          write(value, into: &writer)
          return RustBuffer(bytes: writer)
    }
}
// An error type for FFI errors. These errors occur at the UniFFI level, not
// the library level.
fileprivate enum UniffiInternalError: LocalizedError {
    case bufferOverflow
    case incompleteData
    case unexpectedOptionalTag
    case unexpectedEnumCase
    case unexpectedNullPointer
    case unexpectedRustCallStatusCode
    case unexpectedRustCallError
    case unexpectedStaleHandle
    case rustPanic(_ message: String)

    public var errorDescription: String? {
        switch self {
        case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
        case .incompleteData: return "The buffer still has data after lifting its containing value"
        case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
        case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
        case .unexpectedNullPointer: return "Raw pointer value was null"
        case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
        case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
        case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
        case let .rustPanic(message): return message
        }
    }
}

fileprivate extension NSLock {
    func withLock<T>(f: () throws -> T) rethrows -> T {
        self.lock()
        defer { self.unlock() }
        return try f()
    }
}

fileprivate let CALL_SUCCESS: Int8 = 0
fileprivate let CALL_ERROR: Int8 = 1
fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
fileprivate let CALL_CANCELLED: Int8 = 3

fileprivate extension RustCallStatus {
    init() {
        self.init(
            code: CALL_SUCCESS,
            errorBuf: RustBuffer.init(
                capacity: 0,
                len: 0,
                data: nil
            )
        )
    }
}

private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
    let neverThrow: ((RustBuffer) throws -> Never)? = nil
    return try makeRustCall(callback, errorHandler: neverThrow)
}

private func rustCallWithError<T, E: Swift.Error>(
    _ errorHandler: @escaping (RustBuffer) throws -> E,
    _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
    try makeRustCall(callback, errorHandler: errorHandler)
}

private func makeRustCall<T, E: Swift.Error>(
    _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
    errorHandler: ((RustBuffer) throws -> E)?
) throws -> T {
    uniffiEnsureInitialized()
    var callStatus = RustCallStatus.init()
    let returnedVal = callback(&callStatus)
    try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
    return returnedVal
}

private func uniffiCheckCallStatus<E: Swift.Error>(
    callStatus: RustCallStatus,
    errorHandler: ((RustBuffer) throws -> E)?
) throws {
    switch callStatus.code {
        case CALL_SUCCESS:
            return

        case CALL_ERROR:
            if let errorHandler = errorHandler {
                throw try errorHandler(callStatus.errorBuf)
            } else {
                callStatus.errorBuf.deallocate()
                throw UniffiInternalError.unexpectedRustCallError
            }

        case CALL_UNEXPECTED_ERROR:
            // When the rust code sees a panic, it tries to construct a RustBuffer
            // with the message.  But if that code panics, then it just sends back
            // an empty buffer.
            if callStatus.errorBuf.len > 0 {
                throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
            } else {
                callStatus.errorBuf.deallocate()
                throw UniffiInternalError.rustPanic("Rust panic")
            }

        case CALL_CANCELLED:
            fatalError("Cancellation not supported yet")

        default:
            throw UniffiInternalError.unexpectedRustCallStatusCode
    }
}

private func uniffiTraitInterfaceCall<T>(
    callStatus: UnsafeMutablePointer<RustCallStatus>,
    makeCall: () throws -> T,
    writeReturn: (T) -> ()
) {
    do {
        try writeReturn(makeCall())
    } catch let error {
        callStatus.pointee.code = CALL_UNEXPECTED_ERROR
        callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
    }
}

private func uniffiTraitInterfaceCallWithError<T, E>(
    callStatus: UnsafeMutablePointer<RustCallStatus>,
    makeCall: () throws -> T,
    writeReturn: (T) -> (),
    lowerError: (E) -> RustBuffer
) {
    do {
        try writeReturn(makeCall())
    } catch let error as E {
        callStatus.pointee.code = CALL_ERROR
        callStatus.pointee.errorBuf = lowerError(error)
    } catch {
        callStatus.pointee.code = CALL_UNEXPECTED_ERROR
        callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
    }
}
fileprivate class UniffiHandleMap<T> {
    private var map: [UInt64: T] = [:]
    private let lock = NSLock()
    private var currentHandle: UInt64 = 1

    func insert(obj: T) -> UInt64 {
        lock.withLock {
            let handle = currentHandle
            currentHandle += 1
            map[handle] = obj
            return handle
        }
    }

     func get(handle: UInt64) throws -> T {
        try lock.withLock {
            guard let obj = map[handle] else {
                throw UniffiInternalError.unexpectedStaleHandle
            }
            return obj
        }
    }

    @discardableResult
    func remove(handle: UInt64) throws -> T {
        try lock.withLock {
            guard let obj = map.removeValue(forKey: handle) else {
                throw UniffiInternalError.unexpectedStaleHandle
            }
            return obj
        }
    }

    var count: Int {
        get {
            map.count
        }
    }
}


// Public interface members begin here.


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterInt8: FfiConverterPrimitive {
    typealias FfiType = Int8
    typealias SwiftType = Int8

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Int8 {
        return try lift(readInt(&buf))
    }

    public static func write(_ value: Int8, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterUInt16: FfiConverterPrimitive {
    typealias FfiType = UInt16
    typealias SwiftType = UInt16

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt16 {
        return try lift(readInt(&buf))
    }

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterUInt32: FfiConverterPrimitive {
    typealias FfiType = UInt32
    typealias SwiftType = UInt32

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt32 {
        return try lift(readInt(&buf))
    }

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterUInt64: FfiConverterPrimitive {
    typealias FfiType = UInt64
    typealias SwiftType = UInt64

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 {
        return try lift(readInt(&buf))
    }

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterBool : FfiConverter {
    typealias FfiType = Int8
    typealias SwiftType = Bool

    public static func lift(_ value: Int8) throws -> Bool {
        return value != 0
    }

    public static func lower(_ value: Bool) -> Int8 {
        return value ? 1 : 0
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
        return try lift(readInt(&buf))
    }

    public static func write(_ value: Bool, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterString: FfiConverter {
    typealias SwiftType = String
    typealias FfiType = RustBuffer

    public static func lift(_ value: RustBuffer) throws -> String {
        defer {
            value.deallocate()
        }
        if value.data == nil {
            return String()
        }
        let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
        return String(bytes: bytes, encoding: String.Encoding.utf8)!
    }

    public static func lower(_ value: String) -> RustBuffer {
        return value.utf8CString.withUnsafeBufferPointer { ptr in
            // The swift string gives us int8_t, we want uint8_t.
            ptr.withMemoryRebound(to: UInt8.self) { ptr in
                // The swift string gives us a trailing null byte, we don't want it.
                let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
                return RustBuffer.from(buf)
            }
        }
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
        let len: Int32 = try readInt(&buf)
        return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
    }

    public static func write(_ value: String, into buf: inout [UInt8]) {
        let len = Int32(value.utf8.count)
        writeInt(&buf, len)
        writeBytes(&buf, value.utf8)
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterData: FfiConverterRustBuffer {
    typealias SwiftType = Data

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Data {
        let len: Int32 = try readInt(&buf)
        return Data(try readBytes(&buf, count: Int(len)))
    }

    public static func write(_ value: Data, into buf: inout [UInt8]) {
        let len = Int32(value.count)
        writeInt(&buf, len)
        writeBytes(&buf, value)
    }
}




/**
 * Main Peat BLE adapter interface
 */
public protocol PeatAdapterProtocol : AnyObject {
    
    /**
     * Add a mock discovered peer (for testing)
     */
    func addMockPeer(name: String, rssi: Int8) 
    
    /**
     * Broadcast data to all connected peers
     */
    func broadcastData(data: Data) throws 
    
    /**
     * Connect to a discovered peer by identifier
     */
    func connect(identifier: String) throws 
    
    /**
     * Check if a discovered device matches our mesh
     */
    func deviceMatchesMesh(deviceMeshId: String?)  -> Bool
    
    /**
     * Disconnect from a peer
     */
    func disconnect(peerId: UInt32) throws 
    
    /**
     * Disconnect all peers
     */
    func disconnectAll() 
    
    /**
     * Get current Bluetooth state
     */
    func getBluetoothState()  -> BluetoothState
    
    /**
     * Get connection info for a specific peer
     */
    func getConnection(peerId: UInt32)  -> ConnectionInfo?
    
    /**
     * Get list of active connections
     */
    func getConnections()  -> [ConnectionInfo]
    
    /**
     * Get the BLE device name for this node
     *
     * Format: `PEAT_<MESH_ID>-<NODE_ID>` (e.g., "PEAT_DEMO-12345678")
     */
    func getDeviceName()  -> String
    
    /**
     * Get list of discovered peers
     */
    func getDiscoveredPeers()  -> [DiscoveredPeer]
    
    /**
     * Get the mesh ID this adapter is configured for
     */
    func getMeshId()  -> String
    
    /**
     * Get the local node ID
     */
    func getNodeId()  -> UInt32
    
    /**
     * Get sync statistics
     */
    func getSyncStats()  -> SyncStats
    
    /**
     * Check if advertising is active
     */
    func isAdvertising()  -> Bool
    
    /**
     * Check if scanning is active
     */
    func isDiscovering()  -> Bool
    
    /**
     * Check if the adapter is running
     */
    func isRunning()  -> Bool
    
    /**
     * Process pending events (call periodically from main thread)
     */
    func processEvents() 
    
    /**
     * Send data to a connected peer
     */
    func sendData(peerId: UInt32, data: Data) throws 
    
    /**
     * Set callback for connection events
     */
    func setConnectionCallback(callback: ConnectionCallback) 
    
    /**
     * Set callback for received data
     */
    func setDataCallback(callback: DataCallback) 
    
    /**
     * Set callback for discovery events
     */
    func setDiscoveryCallback(callback: DiscoveryCallback) 
    
    /**
     * Initialize and start the adapter
     */
    func start() throws 
    
    /**
     * Start advertising as an Peat node
     */
    func startAdvertising() throws 
    
    /**
     * Start scanning for Peat peers
     */
    func startDiscovery() throws 
    
    /**
     * Stop the adapter
     */
    func stop() throws 
    
    /**
     * Stop advertising
     */
    func stopAdvertising() throws 
    
    /**
     * Stop scanning
     */
    func stopDiscovery() throws 
    
    /**
     * Trigger manual sync with all connected peers
     */
    func triggerSync() throws 
    
}

/**
 * Main Peat BLE adapter interface
 */
open class PeatAdapter:
    PeatAdapterProtocol {
    fileprivate let pointer: UnsafeMutableRawPointer!

    /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly.
#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public struct NoPointer {
        public init() {}
    }

    // TODO: We'd like this to be `private` but for Swifty reasons,
    // we can't implement `FfiConverter` without making this `required` and we can't
    // make it `required` without making it `public`.
    required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) {
        self.pointer = pointer
    }

    // This constructor can be used to instantiate a fake object.
    // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
    //
    // - Warning:
    //     Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash.
#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public init(noPointer: NoPointer) {
        self.pointer = nil
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public func uniffiClonePointer() -> UnsafeMutableRawPointer {
        return try! rustCall { uniffi_peat_apple_ffi_fn_clone_hiveadapter(self.pointer, $0) }
    }
    /**
     * Create a new adapter with the given node ID and default mesh ID ("DEMO")
     */
public convenience init(nodeId: UInt32)throws  {
    let pointer =
        try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_constructor_hiveadapter_new(
        FfiConverterUInt32.lower(nodeId),$0
    )
}
    self.init(unsafeFromRawPointer: pointer)
}

    deinit {
        guard let pointer = pointer else {
            return
        }

        try! rustCall { uniffi_peat_apple_ffi_fn_free_hiveadapter(pointer, $0) }
    }

    
    /**
     * Create a new adapter with a specific mesh ID
     */
public static func withMeshId(nodeId: UInt32, meshId: String)throws  -> PeatAdapter {
    return try  FfiConverterTypePeatAdapter.lift(try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_constructor_hiveadapter_with_mesh_id(
        FfiConverterUInt32.lower(nodeId),
        FfiConverterString.lower(meshId),$0
    )
})
}
    

    
    /**
     * Add a mock discovered peer (for testing)
     */
open func addMockPeer(name: String, rssi: Int8) {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_add_mock_peer(self.uniffiClonePointer(),
        FfiConverterString.lower(name),
        FfiConverterInt8.lower(rssi),$0
    )
}
}
    
    /**
     * Broadcast data to all connected peers
     */
open func broadcastData(data: Data)throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_broadcast_data(self.uniffiClonePointer(),
        FfiConverterData.lower(data),$0
    )
}
}
    
    /**
     * Connect to a discovered peer by identifier
     */
open func connect(identifier: String)throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_connect(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),$0
    )
}
}
    
    /**
     * Check if a discovered device matches our mesh
     */
open func deviceMatchesMesh(deviceMeshId: String?) -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_device_matches_mesh(self.uniffiClonePointer(),
        FfiConverterOptionString.lower(deviceMeshId),$0
    )
})
}
    
    /**
     * Disconnect from a peer
     */
open func disconnect(peerId: UInt32)throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_disconnect(self.uniffiClonePointer(),
        FfiConverterUInt32.lower(peerId),$0
    )
}
}
    
    /**
     * Disconnect all peers
     */
open func disconnectAll() {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_disconnect_all(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Get current Bluetooth state
     */
open func getBluetoothState() -> BluetoothState {
    return try!  FfiConverterTypeBluetoothState.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_bluetooth_state(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get connection info for a specific peer
     */
open func getConnection(peerId: UInt32) -> ConnectionInfo? {
    return try!  FfiConverterOptionTypeConnectionInfo.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_connection(self.uniffiClonePointer(),
        FfiConverterUInt32.lower(peerId),$0
    )
})
}
    
    /**
     * Get list of active connections
     */
open func getConnections() -> [ConnectionInfo] {
    return try!  FfiConverterSequenceTypeConnectionInfo.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_connections(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get the BLE device name for this node
     *
     * Format: `PEAT_<MESH_ID>-<NODE_ID>` (e.g., "PEAT_DEMO-12345678")
     */
open func getDeviceName() -> String {
    return try!  FfiConverterString.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_device_name(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get list of discovered peers
     */
open func getDiscoveredPeers() -> [DiscoveredPeer] {
    return try!  FfiConverterSequenceTypeDiscoveredPeer.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_discovered_peers(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get the mesh ID this adapter is configured for
     */
open func getMeshId() -> String {
    return try!  FfiConverterString.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_mesh_id(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get the local node ID
     */
open func getNodeId() -> UInt32 {
    return try!  FfiConverterUInt32.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_node_id(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get sync statistics
     */
open func getSyncStats() -> SyncStats {
    return try!  FfiConverterTypeSyncStats.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_get_sync_stats(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if advertising is active
     */
open func isAdvertising() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_is_advertising(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if scanning is active
     */
open func isDiscovering() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_is_discovering(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if the adapter is running
     */
open func isRunning() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_is_running(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Process pending events (call periodically from main thread)
     */
open func processEvents() {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_process_events(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Send data to a connected peer
     */
open func sendData(peerId: UInt32, data: Data)throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_send_data(self.uniffiClonePointer(),
        FfiConverterUInt32.lower(peerId),
        FfiConverterData.lower(data),$0
    )
}
}
    
    /**
     * Set callback for connection events
     */
open func setConnectionCallback(callback: ConnectionCallback) {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_set_connection_callback(self.uniffiClonePointer(),
        FfiConverterCallbackInterfaceConnectionCallback.lower(callback),$0
    )
}
}
    
    /**
     * Set callback for received data
     */
open func setDataCallback(callback: DataCallback) {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_set_data_callback(self.uniffiClonePointer(),
        FfiConverterCallbackInterfaceDataCallback.lower(callback),$0
    )
}
}
    
    /**
     * Set callback for discovery events
     */
open func setDiscoveryCallback(callback: DiscoveryCallback) {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_set_discovery_callback(self.uniffiClonePointer(),
        FfiConverterCallbackInterfaceDiscoveryCallback.lower(callback),$0
    )
}
}
    
    /**
     * Initialize and start the adapter
     */
open func start()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_start(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Start advertising as an Peat node
     */
open func startAdvertising()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_start_advertising(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Start scanning for Peat peers
     */
open func startDiscovery()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_start_discovery(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Stop the adapter
     */
open func stop()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_stop(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Stop advertising
     */
open func stopAdvertising()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_stop_advertising(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Stop scanning
     */
open func stopDiscovery()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_stop_discovery(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Trigger manual sync with all connected peers
     */
open func triggerSync()throws  {try rustCallWithError(FfiConverterTypePeatError.lift) {
    uniffi_peat_apple_ffi_fn_method_hiveadapter_trigger_sync(self.uniffiClonePointer(),$0
    )
}
}
    

}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypePeatAdapter: FfiConverter {

    typealias FfiType = UnsafeMutableRawPointer
    typealias SwiftType = PeatAdapter

    public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> PeatAdapter {
        return PeatAdapter(unsafeFromRawPointer: pointer)
    }

    public static func lower(_ value: PeatAdapter) -> UnsafeMutableRawPointer {
        return value.uniffiClonePointer()
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PeatAdapter {
        let v: UInt64 = try readInt(&buf)
        // The Rust code won't compile if a pointer won't fit in a UInt64.
        // We have to go via `UInt` because that's the thing that's the size of a pointer.
        let ptr = UnsafeMutableRawPointer(bitPattern: UInt(truncatingIfNeeded: v))
        if (ptr == nil) {
            throw UniffiInternalError.unexpectedNullPointer
        }
        return try lift(ptr!)
    }

    public static func write(_ value: PeatAdapter, into buf: inout [UInt8]) {
        // This fiddling is because `Int` is the thing that's the same size as a pointer.
        // The Rust code won't compile if a pointer won't fit in a `UInt64`.
        writeInt(&buf, UInt64(bitPattern: Int64(Int(bitPattern: lower(value)))))
    }
}




#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypePeatAdapter_lift(_ pointer: UnsafeMutableRawPointer) throws -> PeatAdapter {
    return try FfiConverterTypePeatAdapter.lift(pointer)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypePeatAdapter_lower(_ value: PeatAdapter) -> UnsafeMutableRawPointer {
    return FfiConverterTypePeatAdapter.lower(value)
}




/**
 * Main PeatMesh wrapper for UniFFI
 */
public protocol PeatMeshWrapperProtocol : AnyObject {
    
    /**
     * Record our ACK for the current emergency
     * Returns the document bytes to broadcast, or None if no emergency is active
     */
    func ackEmergency(timestamp: UInt64)  -> Data?
    
    /**
     * Add an event observer
     */
    func addObserver(callback: MeshEventCallback) 
    
    /**
     * Check if all peers have ACKed the current emergency
     */
    func allPeersAcked()  -> Bool
    
    /**
     * Build current document for sync
     */
    func buildDocument()  -> Data
    
    /**
     * Clear the current emergency event
     */
    func clearEmergency() 
    
    /**
     * Clear the current event
     */
    func clearEvent() 
    
    /**
     * Get connected peer count
     */
    func connectedCount()  -> UInt32
    
    /**
     * Get device name for BLE advertising
     */
    func deviceName()  -> String
    
    /**
     * Get connected peers only
     */
    func getConnectedPeers()  -> [MeshPeer]
    
    /**
     * Get emergency status info
     * Returns (source_node, timestamp, acked_count, pending_count) if emergency is active
     */
    func getEmergencyStatus()  -> EmergencyStatus?
    
    /**
     * Get all known peers
     */
    func getPeers()  -> [MeshPeer]
    
    /**
     * Check if there's an active document-based emergency
     */
    func hasActiveEmergency()  -> Bool
    
    /**
     * Check if a specific peer has ACKed the current emergency
     */
    func hasPeerAcked(peerId: UInt32)  -> Bool
    
    /**
     * Check if ACK is currently active
     */
    func isAckActive()  -> Bool
    
    /**
     * Check if emergency is currently active
     */
    func isEmergencyActive()  -> Bool
    
    /**
     * Check if a device matches our mesh
     */
    func matchesMesh(deviceMeshId: String?)  -> Bool
    
    /**
     * Get mesh ID
     */
    func meshId()  -> String
    
    /**
     * Get local node ID
     */
    func nodeId()  -> UInt32
    
    /**
     * Called when a BLE connection is established
     */
    func onBleConnected(identifier: String, nowMs: UInt64)  -> UInt32?
    
    /**
     * Called when BLE data is received without a known identifier
     *
     * Use this when receiving data from a peripheral (acting as Central)
     * where the identifier doesn't map to a known peer. This method extracts
     * the source node ID from the document itself.
     */
    func onBleData(identifier: String, data: Data, nowMs: UInt64)  -> DataReceivedResult?
    
    /**
     * Called when BLE data is received from a peer
     * Returns merge result if successful
     */
    func onBleDataReceived(identifier: String, data: Data, nowMs: UInt64)  -> DataReceivedResult?
    
    /**
     * Called when a BLE connection is lost
     */
    func onBleDisconnected(identifier: String, reason: MeshDisconnectReason)  -> UInt32?
    
    /**
     * Called when a BLE device is discovered
     * Returns the peer if it's a valid Peat peer, None otherwise
     */
    func onBleDiscovered(identifier: String, name: String?, rssi: Int8, meshId: String?, nowMs: UInt64)  -> MeshPeer?
    
    /**
     * Called when a remote device connects to us (incoming connection)
     */
    func onIncomingConnection(identifier: String, nodeId: UInt32, nowMs: UInt64)  -> Bool
    
    /**
     * Get peer count
     */
    func peerCount()  -> UInt32
    
    /**
     * Send an ACK event (legacy - uses peripheral event only)
     * Returns the document bytes to broadcast via BLE
     */
    func sendAck(timestamp: UInt64)  -> Data
    
    /**
     * Send an emergency event (legacy - uses peripheral event only)
     * Returns the document bytes to broadcast via BLE
     */
    func sendEmergency(timestamp: UInt64)  -> Data
    
    /**
     * Start a new emergency event with ACK tracking for specified peers
     * Returns the document bytes to broadcast via BLE
     */
    func startEmergency(timestamp: UInt64, knownPeers: [UInt32])  -> Data
    
    /**
     * Start a new emergency event with ACK tracking for all known peers
     * Returns the document bytes to broadcast via BLE
     */
    func startEmergencyWithKnownPeers(timestamp: UInt64)  -> Data
    
    /**
     * Call periodically to perform maintenance tasks
     * Returns document bytes if a sync broadcast is needed
     */
    func tick(nowMs: UInt64)  -> Data?
    
    /**
     * Get total counter value
     */
    func totalCount()  -> UInt64
    
}

/**
 * Main PeatMesh wrapper for UniFFI
 */
open class PeatMeshWrapper:
    PeatMeshWrapperProtocol {
    fileprivate let pointer: UnsafeMutableRawPointer!

    /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly.
#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public struct NoPointer {
        public init() {}
    }

    // TODO: We'd like this to be `private` but for Swifty reasons,
    // we can't implement `FfiConverter` without making this `required` and we can't
    // make it `required` without making it `public`.
    required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) {
        self.pointer = pointer
    }

    // This constructor can be used to instantiate a fake object.
    // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
    //
    // - Warning:
    //     Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash.
#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public init(noPointer: NoPointer) {
        self.pointer = nil
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public func uniffiClonePointer() -> UnsafeMutableRawPointer {
        return try! rustCall { uniffi_peat_apple_ffi_fn_clone_hivemeshwrapper(self.pointer, $0) }
    }
    /**
     * Create a new PeatMesh with the given configuration
     */
public convenience init(nodeId: UInt32, callsign: String, meshId: String, peripheralType: MeshPeripheralType) {
    let pointer =
        try! rustCall() {
    uniffi_peat_apple_ffi_fn_constructor_hivemeshwrapper_new(
        FfiConverterUInt32.lower(nodeId),
        FfiConverterString.lower(callsign),
        FfiConverterString.lower(meshId),
        FfiConverterTypeMeshPeripheralType.lower(peripheralType),$0
    )
}
    self.init(unsafeFromRawPointer: pointer)
}

    deinit {
        guard let pointer = pointer else {
            return
        }

        try! rustCall { uniffi_peat_apple_ffi_fn_free_hivemeshwrapper(pointer, $0) }
    }

    
    /**
     * Create with default configuration
     */
public static func withDefaults(nodeId: UInt32, callsign: String) -> PeatMeshWrapper {
    return try!  FfiConverterTypePeatMeshWrapper.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_constructor_hivemeshwrapper_with_defaults(
        FfiConverterUInt32.lower(nodeId),
        FfiConverterString.lower(callsign),$0
    )
})
}
    

    
    /**
     * Record our ACK for the current emergency
     * Returns the document bytes to broadcast, or None if no emergency is active
     */
open func ackEmergency(timestamp: UInt64) -> Data? {
    return try!  FfiConverterOptionData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_ack_emergency(self.uniffiClonePointer(),
        FfiConverterUInt64.lower(timestamp),$0
    )
})
}
    
    /**
     * Add an event observer
     */
open func addObserver(callback: MeshEventCallback) {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_add_observer(self.uniffiClonePointer(),
        FfiConverterCallbackInterfaceMeshEventCallback.lower(callback),$0
    )
}
}
    
    /**
     * Check if all peers have ACKed the current emergency
     */
open func allPeersAcked() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_all_peers_acked(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Build current document for sync
     */
open func buildDocument() -> Data {
    return try!  FfiConverterData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_build_document(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Clear the current emergency event
     */
open func clearEmergency() {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_clear_emergency(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Clear the current event
     */
open func clearEvent() {try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_clear_event(self.uniffiClonePointer(),$0
    )
}
}
    
    /**
     * Get connected peer count
     */
open func connectedCount() -> UInt32 {
    return try!  FfiConverterUInt32.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_connected_count(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get device name for BLE advertising
     */
open func deviceName() -> String {
    return try!  FfiConverterString.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_device_name(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get connected peers only
     */
open func getConnectedPeers() -> [MeshPeer] {
    return try!  FfiConverterSequenceTypeMeshPeer.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_get_connected_peers(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get emergency status info
     * Returns (source_node, timestamp, acked_count, pending_count) if emergency is active
     */
open func getEmergencyStatus() -> EmergencyStatus? {
    return try!  FfiConverterOptionTypeEmergencyStatus.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_get_emergency_status(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get all known peers
     */
open func getPeers() -> [MeshPeer] {
    return try!  FfiConverterSequenceTypeMeshPeer.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_get_peers(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if there's an active document-based emergency
     */
open func hasActiveEmergency() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_has_active_emergency(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if a specific peer has ACKed the current emergency
     */
open func hasPeerAcked(peerId: UInt32) -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_has_peer_acked(self.uniffiClonePointer(),
        FfiConverterUInt32.lower(peerId),$0
    )
})
}
    
    /**
     * Check if ACK is currently active
     */
open func isAckActive() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_is_ack_active(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if emergency is currently active
     */
open func isEmergencyActive() -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_is_emergency_active(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Check if a device matches our mesh
     */
open func matchesMesh(deviceMeshId: String?) -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_matches_mesh(self.uniffiClonePointer(),
        FfiConverterOptionString.lower(deviceMeshId),$0
    )
})
}
    
    /**
     * Get mesh ID
     */
open func meshId() -> String {
    return try!  FfiConverterString.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_mesh_id(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Get local node ID
     */
open func nodeId() -> UInt32 {
    return try!  FfiConverterUInt32.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_node_id(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Called when a BLE connection is established
     */
open func onBleConnected(identifier: String, nowMs: UInt64) -> UInt32? {
    return try!  FfiConverterOptionUInt32.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_on_ble_connected(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),
        FfiConverterUInt64.lower(nowMs),$0
    )
})
}
    
    /**
     * Called when BLE data is received without a known identifier
     *
     * Use this when receiving data from a peripheral (acting as Central)
     * where the identifier doesn't map to a known peer. This method extracts
     * the source node ID from the document itself.
     */
open func onBleData(identifier: String, data: Data, nowMs: UInt64) -> DataReceivedResult? {
    return try!  FfiConverterOptionTypeDataReceivedResult.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_on_ble_data(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),
        FfiConverterData.lower(data),
        FfiConverterUInt64.lower(nowMs),$0
    )
})
}
    
    /**
     * Called when BLE data is received from a peer
     * Returns merge result if successful
     */
open func onBleDataReceived(identifier: String, data: Data, nowMs: UInt64) -> DataReceivedResult? {
    return try!  FfiConverterOptionTypeDataReceivedResult.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_on_ble_data_received(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),
        FfiConverterData.lower(data),
        FfiConverterUInt64.lower(nowMs),$0
    )
})
}
    
    /**
     * Called when a BLE connection is lost
     */
open func onBleDisconnected(identifier: String, reason: MeshDisconnectReason) -> UInt32? {
    return try!  FfiConverterOptionUInt32.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_on_ble_disconnected(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),
        FfiConverterTypeMeshDisconnectReason.lower(reason),$0
    )
})
}
    
    /**
     * Called when a BLE device is discovered
     * Returns the peer if it's a valid Peat peer, None otherwise
     */
open func onBleDiscovered(identifier: String, name: String?, rssi: Int8, meshId: String?, nowMs: UInt64) -> MeshPeer? {
    return try!  FfiConverterOptionTypeMeshPeer.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_on_ble_discovered(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),
        FfiConverterOptionString.lower(name),
        FfiConverterInt8.lower(rssi),
        FfiConverterOptionString.lower(meshId),
        FfiConverterUInt64.lower(nowMs),$0
    )
})
}
    
    /**
     * Called when a remote device connects to us (incoming connection)
     */
open func onIncomingConnection(identifier: String, nodeId: UInt32, nowMs: UInt64) -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_on_incoming_connection(self.uniffiClonePointer(),
        FfiConverterString.lower(identifier),
        FfiConverterUInt32.lower(nodeId),
        FfiConverterUInt64.lower(nowMs),$0
    )
})
}
    
    /**
     * Get peer count
     */
open func peerCount() -> UInt32 {
    return try!  FfiConverterUInt32.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_peer_count(self.uniffiClonePointer(),$0
    )
})
}
    
    /**
     * Send an ACK event (legacy - uses peripheral event only)
     * Returns the document bytes to broadcast via BLE
     */
open func sendAck(timestamp: UInt64) -> Data {
    return try!  FfiConverterData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_send_ack(self.uniffiClonePointer(),
        FfiConverterUInt64.lower(timestamp),$0
    )
})
}
    
    /**
     * Send an emergency event (legacy - uses peripheral event only)
     * Returns the document bytes to broadcast via BLE
     */
open func sendEmergency(timestamp: UInt64) -> Data {
    return try!  FfiConverterData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_send_emergency(self.uniffiClonePointer(),
        FfiConverterUInt64.lower(timestamp),$0
    )
})
}
    
    /**
     * Start a new emergency event with ACK tracking for specified peers
     * Returns the document bytes to broadcast via BLE
     */
open func startEmergency(timestamp: UInt64, knownPeers: [UInt32]) -> Data {
    return try!  FfiConverterData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_start_emergency(self.uniffiClonePointer(),
        FfiConverterUInt64.lower(timestamp),
        FfiConverterSequenceUInt32.lower(knownPeers),$0
    )
})
}
    
    /**
     * Start a new emergency event with ACK tracking for all known peers
     * Returns the document bytes to broadcast via BLE
     */
open func startEmergencyWithKnownPeers(timestamp: UInt64) -> Data {
    return try!  FfiConverterData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_start_emergency_with_known_peers(self.uniffiClonePointer(),
        FfiConverterUInt64.lower(timestamp),$0
    )
})
}
    
    /**
     * Call periodically to perform maintenance tasks
     * Returns document bytes if a sync broadcast is needed
     */
open func tick(nowMs: UInt64) -> Data? {
    return try!  FfiConverterOptionData.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_tick(self.uniffiClonePointer(),
        FfiConverterUInt64.lower(nowMs),$0
    )
})
}
    
    /**
     * Get total counter value
     */
open func totalCount() -> UInt64 {
    return try!  FfiConverterUInt64.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_method_hivemeshwrapper_total_count(self.uniffiClonePointer(),$0
    )
})
}
    

}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypePeatMeshWrapper: FfiConverter {

    typealias FfiType = UnsafeMutableRawPointer
    typealias SwiftType = PeatMeshWrapper

    public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> PeatMeshWrapper {
        return PeatMeshWrapper(unsafeFromRawPointer: pointer)
    }

    public static func lower(_ value: PeatMeshWrapper) -> UnsafeMutableRawPointer {
        return value.uniffiClonePointer()
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PeatMeshWrapper {
        let v: UInt64 = try readInt(&buf)
        // The Rust code won't compile if a pointer won't fit in a UInt64.
        // We have to go via `UInt` because that's the thing that's the size of a pointer.
        let ptr = UnsafeMutableRawPointer(bitPattern: UInt(truncatingIfNeeded: v))
        if (ptr == nil) {
            throw UniffiInternalError.unexpectedNullPointer
        }
        return try lift(ptr!)
    }

    public static func write(_ value: PeatMeshWrapper, into buf: inout [UInt8]) {
        // This fiddling is because `Int` is the thing that's the same size as a pointer.
        // The Rust code won't compile if a pointer won't fit in a `UInt64`.
        writeInt(&buf, UInt64(bitPattern: Int64(Int(bitPattern: lower(value)))))
    }
}




#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypePeatMeshWrapper_lift(_ pointer: UnsafeMutableRawPointer) throws -> PeatMeshWrapper {
    return try FfiConverterTypePeatMeshWrapper.lift(pointer)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypePeatMeshWrapper_lower(_ value: PeatMeshWrapper) -> UnsafeMutableRawPointer {
    return FfiConverterTypePeatMeshWrapper.lower(value)
}


/**
 * Information about an active connection
 */
public struct ConnectionInfo {
    public var peerId: UInt32
    public var identifier: String
    public var mtu: UInt16
    public var phy: BlePhy
    public var rssi: Int8?
    public var isAlive: Bool

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(peerId: UInt32, identifier: String, mtu: UInt16, phy: BlePhy, rssi: Int8?, isAlive: Bool) {
        self.peerId = peerId
        self.identifier = identifier
        self.mtu = mtu
        self.phy = phy
        self.rssi = rssi
        self.isAlive = isAlive
    }
}



extension ConnectionInfo: Equatable, Hashable {
    public static func ==(lhs: ConnectionInfo, rhs: ConnectionInfo) -> Bool {
        if lhs.peerId != rhs.peerId {
            return false
        }
        if lhs.identifier != rhs.identifier {
            return false
        }
        if lhs.mtu != rhs.mtu {
            return false
        }
        if lhs.phy != rhs.phy {
            return false
        }
        if lhs.rssi != rhs.rssi {
            return false
        }
        if lhs.isAlive != rhs.isAlive {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(peerId)
        hasher.combine(identifier)
        hasher.combine(mtu)
        hasher.combine(phy)
        hasher.combine(rssi)
        hasher.combine(isAlive)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeConnectionInfo: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ConnectionInfo {
        return
            try ConnectionInfo(
                peerId: FfiConverterUInt32.read(from: &buf), 
                identifier: FfiConverterString.read(from: &buf), 
                mtu: FfiConverterUInt16.read(from: &buf), 
                phy: FfiConverterTypeBlePhy.read(from: &buf), 
                rssi: FfiConverterOptionInt8.read(from: &buf), 
                isAlive: FfiConverterBool.read(from: &buf)
        )
    }

    public static func write(_ value: ConnectionInfo, into buf: inout [UInt8]) {
        FfiConverterUInt32.write(value.peerId, into: &buf)
        FfiConverterString.write(value.identifier, into: &buf)
        FfiConverterUInt16.write(value.mtu, into: &buf)
        FfiConverterTypeBlePhy.write(value.phy, into: &buf)
        FfiConverterOptionInt8.write(value.rssi, into: &buf)
        FfiConverterBool.write(value.isAlive, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeConnectionInfo_lift(_ buf: RustBuffer) throws -> ConnectionInfo {
    return try FfiConverterTypeConnectionInfo.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeConnectionInfo_lower(_ value: ConnectionInfo) -> RustBuffer {
    return FfiConverterTypeConnectionInfo.lower(value)
}


/**
 * Result of receiving BLE data
 */
public struct DataReceivedResult {
    /**
     * Node ID of sender
     */
    public var sourceNode: UInt32
    /**
     * Whether document contained an emergency event
     */
    public var isEmergency: Bool
    /**
     * Whether document contained an ACK event
     */
    public var isAck: Bool
    /**
     * Whether counter changed (new data)
     */
    public var counterChanged: Bool
    /**
     * Whether emergency state changed (new emergency or ACK updates)
     */
    public var emergencyChanged: Bool
    /**
     * Total counter value after merge
     */
    public var totalCount: UInt64
    /**
     * Event timestamp (0 if no event) - use to detect duplicate events
     */
    public var eventTimestamp: UInt64

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(
        /**
         * Node ID of sender
         */sourceNode: UInt32, 
        /**
         * Whether document contained an emergency event
         */isEmergency: Bool, 
        /**
         * Whether document contained an ACK event
         */isAck: Bool, 
        /**
         * Whether counter changed (new data)
         */counterChanged: Bool, 
        /**
         * Whether emergency state changed (new emergency or ACK updates)
         */emergencyChanged: Bool, 
        /**
         * Total counter value after merge
         */totalCount: UInt64, 
        /**
         * Event timestamp (0 if no event) - use to detect duplicate events
         */eventTimestamp: UInt64) {
        self.sourceNode = sourceNode
        self.isEmergency = isEmergency
        self.isAck = isAck
        self.counterChanged = counterChanged
        self.emergencyChanged = emergencyChanged
        self.totalCount = totalCount
        self.eventTimestamp = eventTimestamp
    }
}



extension DataReceivedResult: Equatable, Hashable {
    public static func ==(lhs: DataReceivedResult, rhs: DataReceivedResult) -> Bool {
        if lhs.sourceNode != rhs.sourceNode {
            return false
        }
        if lhs.isEmergency != rhs.isEmergency {
            return false
        }
        if lhs.isAck != rhs.isAck {
            return false
        }
        if lhs.counterChanged != rhs.counterChanged {
            return false
        }
        if lhs.emergencyChanged != rhs.emergencyChanged {
            return false
        }
        if lhs.totalCount != rhs.totalCount {
            return false
        }
        if lhs.eventTimestamp != rhs.eventTimestamp {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(sourceNode)
        hasher.combine(isEmergency)
        hasher.combine(isAck)
        hasher.combine(counterChanged)
        hasher.combine(emergencyChanged)
        hasher.combine(totalCount)
        hasher.combine(eventTimestamp)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeDataReceivedResult: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DataReceivedResult {
        return
            try DataReceivedResult(
                sourceNode: FfiConverterUInt32.read(from: &buf), 
                isEmergency: FfiConverterBool.read(from: &buf), 
                isAck: FfiConverterBool.read(from: &buf), 
                counterChanged: FfiConverterBool.read(from: &buf), 
                emergencyChanged: FfiConverterBool.read(from: &buf), 
                totalCount: FfiConverterUInt64.read(from: &buf), 
                eventTimestamp: FfiConverterUInt64.read(from: &buf)
        )
    }

    public static func write(_ value: DataReceivedResult, into buf: inout [UInt8]) {
        FfiConverterUInt32.write(value.sourceNode, into: &buf)
        FfiConverterBool.write(value.isEmergency, into: &buf)
        FfiConverterBool.write(value.isAck, into: &buf)
        FfiConverterBool.write(value.counterChanged, into: &buf)
        FfiConverterBool.write(value.emergencyChanged, into: &buf)
        FfiConverterUInt64.write(value.totalCount, into: &buf)
        FfiConverterUInt64.write(value.eventTimestamp, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeDataReceivedResult_lift(_ buf: RustBuffer) throws -> DataReceivedResult {
    return try FfiConverterTypeDataReceivedResult.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeDataReceivedResult_lower(_ value: DataReceivedResult) -> RustBuffer {
    return FfiConverterTypeDataReceivedResult.lower(value)
}


/**
 * Information about a discovered BLE device
 */
public struct DiscoveredPeer {
    public var identifier: String
    public var name: String?
    public var rssi: Int8
    public var nodeId: UInt32?
    public var isPeatNode: Bool

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(identifier: String, name: String?, rssi: Int8, nodeId: UInt32?, isPeatNode: Bool) {
        self.identifier = identifier
        self.name = name
        self.rssi = rssi
        self.nodeId = nodeId
        self.isPeatNode = isPeatNode
    }
}



extension DiscoveredPeer: Equatable, Hashable {
    public static func ==(lhs: DiscoveredPeer, rhs: DiscoveredPeer) -> Bool {
        if lhs.identifier != rhs.identifier {
            return false
        }
        if lhs.name != rhs.name {
            return false
        }
        if lhs.rssi != rhs.rssi {
            return false
        }
        if lhs.nodeId != rhs.nodeId {
            return false
        }
        if lhs.isPeatNode != rhs.isPeatNode {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(identifier)
        hasher.combine(name)
        hasher.combine(rssi)
        hasher.combine(nodeId)
        hasher.combine(isPeatNode)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeDiscoveredPeer: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DiscoveredPeer {
        return
            try DiscoveredPeer(
                identifier: FfiConverterString.read(from: &buf), 
                name: FfiConverterOptionString.read(from: &buf), 
                rssi: FfiConverterInt8.read(from: &buf), 
                nodeId: FfiConverterOptionUInt32.read(from: &buf), 
                isPeatNode: FfiConverterBool.read(from: &buf)
        )
    }

    public static func write(_ value: DiscoveredPeer, into buf: inout [UInt8]) {
        FfiConverterString.write(value.identifier, into: &buf)
        FfiConverterOptionString.write(value.name, into: &buf)
        FfiConverterInt8.write(value.rssi, into: &buf)
        FfiConverterOptionUInt32.write(value.nodeId, into: &buf)
        FfiConverterBool.write(value.isPeatNode, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeDiscoveredPeer_lift(_ buf: RustBuffer) throws -> DiscoveredPeer {
    return try FfiConverterTypeDiscoveredPeer.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeDiscoveredPeer_lower(_ value: DiscoveredPeer) -> RustBuffer {
    return FfiConverterTypeDiscoveredPeer.lower(value)
}


/**
 * Status of an active emergency event with ACK tracking
 */
public struct EmergencyStatus {
    /**
     * Node ID that started the emergency
     */
    public var sourceNode: UInt32
    /**
     * Timestamp when emergency was started
     */
    public var timestamp: UInt64
    /**
     * Number of peers that have ACKed
     */
    public var ackedCount: UInt32
    /**
     * Number of peers still pending ACK
     */
    public var pendingCount: UInt32

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(
        /**
         * Node ID that started the emergency
         */sourceNode: UInt32, 
        /**
         * Timestamp when emergency was started
         */timestamp: UInt64, 
        /**
         * Number of peers that have ACKed
         */ackedCount: UInt32, 
        /**
         * Number of peers still pending ACK
         */pendingCount: UInt32) {
        self.sourceNode = sourceNode
        self.timestamp = timestamp
        self.ackedCount = ackedCount
        self.pendingCount = pendingCount
    }
}



extension EmergencyStatus: Equatable, Hashable {
    public static func ==(lhs: EmergencyStatus, rhs: EmergencyStatus) -> Bool {
        if lhs.sourceNode != rhs.sourceNode {
            return false
        }
        if lhs.timestamp != rhs.timestamp {
            return false
        }
        if lhs.ackedCount != rhs.ackedCount {
            return false
        }
        if lhs.pendingCount != rhs.pendingCount {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(sourceNode)
        hasher.combine(timestamp)
        hasher.combine(ackedCount)
        hasher.combine(pendingCount)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeEmergencyStatus: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> EmergencyStatus {
        return
            try EmergencyStatus(
                sourceNode: FfiConverterUInt32.read(from: &buf), 
                timestamp: FfiConverterUInt64.read(from: &buf), 
                ackedCount: FfiConverterUInt32.read(from: &buf), 
                pendingCount: FfiConverterUInt32.read(from: &buf)
        )
    }

    public static func write(_ value: EmergencyStatus, into buf: inout [UInt8]) {
        FfiConverterUInt32.write(value.sourceNode, into: &buf)
        FfiConverterUInt64.write(value.timestamp, into: &buf)
        FfiConverterUInt32.write(value.ackedCount, into: &buf)
        FfiConverterUInt32.write(value.pendingCount, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeEmergencyStatus_lift(_ buf: RustBuffer) throws -> EmergencyStatus {
    return try FfiConverterTypeEmergencyStatus.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeEmergencyStatus_lower(_ value: EmergencyStatus) -> RustBuffer {
    return FfiConverterTypeEmergencyStatus.lower(value)
}


/**
 * UniFFI-compatible peer representation
 */
public struct MeshPeer {
    /**
     * Unique node ID (32-bit)
     */
    public var nodeId: UInt32
    /**
     * Platform-specific identifier (CBPeripheral UUID, MAC address, etc.)
     */
    public var identifier: String
    /**
     * Mesh ID this peer belongs to
     */
    public var meshId: String?
    /**
     * Display name
     */
    public var name: String?
    /**
     * Signal strength (RSSI in dBm)
     */
    public var rssi: Int8
    /**
     * Whether currently connected
     */
    public var isConnected: Bool
    /**
     * Last seen timestamp (milliseconds since epoch)
     */
    public var lastSeenMs: UInt64

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(
        /**
         * Unique node ID (32-bit)
         */nodeId: UInt32, 
        /**
         * Platform-specific identifier (CBPeripheral UUID, MAC address, etc.)
         */identifier: String, 
        /**
         * Mesh ID this peer belongs to
         */meshId: String?, 
        /**
         * Display name
         */name: String?, 
        /**
         * Signal strength (RSSI in dBm)
         */rssi: Int8, 
        /**
         * Whether currently connected
         */isConnected: Bool, 
        /**
         * Last seen timestamp (milliseconds since epoch)
         */lastSeenMs: UInt64) {
        self.nodeId = nodeId
        self.identifier = identifier
        self.meshId = meshId
        self.name = name
        self.rssi = rssi
        self.isConnected = isConnected
        self.lastSeenMs = lastSeenMs
    }
}



extension MeshPeer: Equatable, Hashable {
    public static func ==(lhs: MeshPeer, rhs: MeshPeer) -> Bool {
        if lhs.nodeId != rhs.nodeId {
            return false
        }
        if lhs.identifier != rhs.identifier {
            return false
        }
        if lhs.meshId != rhs.meshId {
            return false
        }
        if lhs.name != rhs.name {
            return false
        }
        if lhs.rssi != rhs.rssi {
            return false
        }
        if lhs.isConnected != rhs.isConnected {
            return false
        }
        if lhs.lastSeenMs != rhs.lastSeenMs {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(nodeId)
        hasher.combine(identifier)
        hasher.combine(meshId)
        hasher.combine(name)
        hasher.combine(rssi)
        hasher.combine(isConnected)
        hasher.combine(lastSeenMs)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeMeshPeer: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> MeshPeer {
        return
            try MeshPeer(
                nodeId: FfiConverterUInt32.read(from: &buf), 
                identifier: FfiConverterString.read(from: &buf), 
                meshId: FfiConverterOptionString.read(from: &buf), 
                name: FfiConverterOptionString.read(from: &buf), 
                rssi: FfiConverterInt8.read(from: &buf), 
                isConnected: FfiConverterBool.read(from: &buf), 
                lastSeenMs: FfiConverterUInt64.read(from: &buf)
        )
    }

    public static func write(_ value: MeshPeer, into buf: inout [UInt8]) {
        FfiConverterUInt32.write(value.nodeId, into: &buf)
        FfiConverterString.write(value.identifier, into: &buf)
        FfiConverterOptionString.write(value.meshId, into: &buf)
        FfiConverterOptionString.write(value.name, into: &buf)
        FfiConverterInt8.write(value.rssi, into: &buf)
        FfiConverterBool.write(value.isConnected, into: &buf)
        FfiConverterUInt64.write(value.lastSeenMs, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshPeer_lift(_ buf: RustBuffer) throws -> MeshPeer {
    return try FfiConverterTypeMeshPeer.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshPeer_lower(_ value: MeshPeer) -> RustBuffer {
    return FfiConverterTypeMeshPeer.lower(value)
}


/**
 * Parsed device name result
 */
public struct ParsedDeviceName {
    /**
     * Mesh ID (None for legacy PEAT- format)
     */
    public var meshId: String?
    /**
     * Node ID
     */
    public var nodeId: UInt32

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(
        /**
         * Mesh ID (None for legacy PEAT- format)
         */meshId: String?, 
        /**
         * Node ID
         */nodeId: UInt32) {
        self.meshId = meshId
        self.nodeId = nodeId
    }
}



extension ParsedDeviceName: Equatable, Hashable {
    public static func ==(lhs: ParsedDeviceName, rhs: ParsedDeviceName) -> Bool {
        if lhs.meshId != rhs.meshId {
            return false
        }
        if lhs.nodeId != rhs.nodeId {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(meshId)
        hasher.combine(nodeId)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeParsedDeviceName: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ParsedDeviceName {
        return
            try ParsedDeviceName(
                meshId: FfiConverterOptionString.read(from: &buf), 
                nodeId: FfiConverterUInt32.read(from: &buf)
        )
    }

    public static func write(_ value: ParsedDeviceName, into buf: inout [UInt8]) {
        FfiConverterOptionString.write(value.meshId, into: &buf)
        FfiConverterUInt32.write(value.nodeId, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeParsedDeviceName_lift(_ buf: RustBuffer) throws -> ParsedDeviceName {
    return try FfiConverterTypeParsedDeviceName.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeParsedDeviceName_lower(_ value: ParsedDeviceName) -> RustBuffer {
    return FfiConverterTypeParsedDeviceName.lower(value)
}


/**
 * Sync statistics
 */
public struct SyncStats {
    public var documentCount: UInt32
    public var pendingChanges: UInt32
    public var bytesSynced: UInt64
    public var lastSyncTimestamp: UInt64?

    // Default memberwise initializers are never public by default, so we
    // declare one manually.
    public init(documentCount: UInt32, pendingChanges: UInt32, bytesSynced: UInt64, lastSyncTimestamp: UInt64?) {
        self.documentCount = documentCount
        self.pendingChanges = pendingChanges
        self.bytesSynced = bytesSynced
        self.lastSyncTimestamp = lastSyncTimestamp
    }
}



extension SyncStats: Equatable, Hashable {
    public static func ==(lhs: SyncStats, rhs: SyncStats) -> Bool {
        if lhs.documentCount != rhs.documentCount {
            return false
        }
        if lhs.pendingChanges != rhs.pendingChanges {
            return false
        }
        if lhs.bytesSynced != rhs.bytesSynced {
            return false
        }
        if lhs.lastSyncTimestamp != rhs.lastSyncTimestamp {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(documentCount)
        hasher.combine(pendingChanges)
        hasher.combine(bytesSynced)
        hasher.combine(lastSyncTimestamp)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeSyncStats: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SyncStats {
        return
            try SyncStats(
                documentCount: FfiConverterUInt32.read(from: &buf), 
                pendingChanges: FfiConverterUInt32.read(from: &buf), 
                bytesSynced: FfiConverterUInt64.read(from: &buf), 
                lastSyncTimestamp: FfiConverterOptionUInt64.read(from: &buf)
        )
    }

    public static func write(_ value: SyncStats, into buf: inout [UInt8]) {
        FfiConverterUInt32.write(value.documentCount, into: &buf)
        FfiConverterUInt32.write(value.pendingChanges, into: &buf)
        FfiConverterUInt64.write(value.bytesSynced, into: &buf)
        FfiConverterOptionUInt64.write(value.lastSyncTimestamp, into: &buf)
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeSyncStats_lift(_ buf: RustBuffer) throws -> SyncStats {
    return try FfiConverterTypeSyncStats.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeSyncStats_lower(_ value: SyncStats) -> RustBuffer {
    return FfiConverterTypeSyncStats.lower(value)
}

// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
 * BLE PHY mode
 */

public enum BlePhy {
    
    case le1M
    case le2M
    case leCoded
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeBlePhy: FfiConverterRustBuffer {
    typealias SwiftType = BlePhy

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> BlePhy {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        
        case 1: return .le1M
        
        case 2: return .le2M
        
        case 3: return .leCoded
        
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: BlePhy, into buf: inout [UInt8]) {
        switch value {
        
        
        case .le1M:
            writeInt(&buf, Int32(1))
        
        
        case .le2M:
            writeInt(&buf, Int32(2))
        
        
        case .leCoded:
            writeInt(&buf, Int32(3))
        
        }
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeBlePhy_lift(_ buf: RustBuffer) throws -> BlePhy {
    return try FfiConverterTypeBlePhy.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeBlePhy_lower(_ value: BlePhy) -> RustBuffer {
    return FfiConverterTypeBlePhy.lower(value)
}



extension BlePhy: Equatable, Hashable {}



// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
 * Bluetooth adapter state
 */

public enum BluetoothState {
    
    case unknown
    case resetting
    case unsupported
    case unauthorized
    case poweredOff
    case poweredOn
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeBluetoothState: FfiConverterRustBuffer {
    typealias SwiftType = BluetoothState

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> BluetoothState {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        
        case 1: return .unknown
        
        case 2: return .resetting
        
        case 3: return .unsupported
        
        case 4: return .unauthorized
        
        case 5: return .poweredOff
        
        case 6: return .poweredOn
        
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: BluetoothState, into buf: inout [UInt8]) {
        switch value {
        
        
        case .unknown:
            writeInt(&buf, Int32(1))
        
        
        case .resetting:
            writeInt(&buf, Int32(2))
        
        
        case .unsupported:
            writeInt(&buf, Int32(3))
        
        
        case .unauthorized:
            writeInt(&buf, Int32(4))
        
        
        case .poweredOff:
            writeInt(&buf, Int32(5))
        
        
        case .poweredOn:
            writeInt(&buf, Int32(6))
        
        }
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeBluetoothState_lift(_ buf: RustBuffer) throws -> BluetoothState {
    return try FfiConverterTypeBluetoothState.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeBluetoothState_lower(_ value: BluetoothState) -> RustBuffer {
    return FfiConverterTypeBluetoothState.lower(value)
}



extension BluetoothState: Equatable, Hashable {}




/**
 * Error types for the Peat adapter
 */
public enum PeatError {

    
    
    case NotInitialized
    case AlreadyInitialized
    case NotRunning
    case BluetoothUnavailable
    case BluetoothUnauthorized
    case ConnectionFailed(reason: String
    )
    case SendFailed(reason: String
    )
    case Timeout
    case InvalidState
    case Internal(message: String
    )
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypePeatError: FfiConverterRustBuffer {
    typealias SwiftType = PeatError

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PeatError {
        let variant: Int32 = try readInt(&buf)
        switch variant {

        

        
        case 1: return .NotInitialized
        case 2: return .AlreadyInitialized
        case 3: return .NotRunning
        case 4: return .BluetoothUnavailable
        case 5: return .BluetoothUnauthorized
        case 6: return .ConnectionFailed(
            reason: try FfiConverterString.read(from: &buf)
            )
        case 7: return .SendFailed(
            reason: try FfiConverterString.read(from: &buf)
            )
        case 8: return .Timeout
        case 9: return .InvalidState
        case 10: return .Internal(
            message: try FfiConverterString.read(from: &buf)
            )

         default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: PeatError, into buf: inout [UInt8]) {
        switch value {

        

        
        
        case .NotInitialized:
            writeInt(&buf, Int32(1))
        
        
        case .AlreadyInitialized:
            writeInt(&buf, Int32(2))
        
        
        case .NotRunning:
            writeInt(&buf, Int32(3))
        
        
        case .BluetoothUnavailable:
            writeInt(&buf, Int32(4))
        
        
        case .BluetoothUnauthorized:
            writeInt(&buf, Int32(5))
        
        
        case let .ConnectionFailed(reason):
            writeInt(&buf, Int32(6))
            FfiConverterString.write(reason, into: &buf)
            
        
        case let .SendFailed(reason):
            writeInt(&buf, Int32(7))
            FfiConverterString.write(reason, into: &buf)
            
        
        case .Timeout:
            writeInt(&buf, Int32(8))
        
        
        case .InvalidState:
            writeInt(&buf, Int32(9))
        
        
        case let .Internal(message):
            writeInt(&buf, Int32(10))
            FfiConverterString.write(message, into: &buf)
            
        }
    }
}


extension PeatError: Equatable, Hashable {}

extension PeatError: Foundation.LocalizedError {
    public var errorDescription: String? {
        String(reflecting: self)
    }
}

// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
 * Disconnect reason
 */

public enum MeshDisconnectReason {
    
    case localRequest
    case remoteRequest
    case timeout
    case linkLoss
    case connectionFailed
    case unknown
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeMeshDisconnectReason: FfiConverterRustBuffer {
    typealias SwiftType = MeshDisconnectReason

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> MeshDisconnectReason {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        
        case 1: return .localRequest
        
        case 2: return .remoteRequest
        
        case 3: return .timeout
        
        case 4: return .linkLoss
        
        case 5: return .connectionFailed
        
        case 6: return .unknown
        
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: MeshDisconnectReason, into buf: inout [UInt8]) {
        switch value {
        
        
        case .localRequest:
            writeInt(&buf, Int32(1))
        
        
        case .remoteRequest:
            writeInt(&buf, Int32(2))
        
        
        case .timeout:
            writeInt(&buf, Int32(3))
        
        
        case .linkLoss:
            writeInt(&buf, Int32(4))
        
        
        case .connectionFailed:
            writeInt(&buf, Int32(5))
        
        
        case .unknown:
            writeInt(&buf, Int32(6))
        
        }
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshDisconnectReason_lift(_ buf: RustBuffer) throws -> MeshDisconnectReason {
    return try FfiConverterTypeMeshDisconnectReason.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshDisconnectReason_lower(_ value: MeshDisconnectReason) -> RustBuffer {
    return FfiConverterTypeMeshDisconnectReason.lower(value)
}



extension MeshDisconnectReason: Equatable, Hashable {}



// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
 * Event received from the mesh
 */

public enum MeshEvent {
    
    /**
     * New peer discovered
     */
    case peerDiscovered(peer: MeshPeer
    )
    /**
     * Peer connected
     */
    case peerConnected(nodeId: UInt32
    )
    /**
     * Peer disconnected
     */
    case peerDisconnected(nodeId: UInt32, reason: MeshDisconnectReason
    )
    /**
     * Peer lost (cleanup timeout)
     */
    case peerLost(nodeId: UInt32
    )
    /**
     * Emergency received from peer
     */
    case emergencyReceived(fromNode: UInt32
    )
    /**
     * ACK received from peer
     */
    case ackReceived(fromNode: UInt32
    )
    /**
     * Document synced with peer
     */
    case documentSynced(fromNode: UInt32, totalCount: UInt64
    )
    /**
     * Mesh state changed (peer count, etc.)
     */
    case meshStateChanged(peerCount: UInt32, connectedCount: UInt32
    )
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeMeshEvent: FfiConverterRustBuffer {
    typealias SwiftType = MeshEvent

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> MeshEvent {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        
        case 1: return .peerDiscovered(peer: try FfiConverterTypeMeshPeer.read(from: &buf)
        )
        
        case 2: return .peerConnected(nodeId: try FfiConverterUInt32.read(from: &buf)
        )
        
        case 3: return .peerDisconnected(nodeId: try FfiConverterUInt32.read(from: &buf), reason: try FfiConverterTypeMeshDisconnectReason.read(from: &buf)
        )
        
        case 4: return .peerLost(nodeId: try FfiConverterUInt32.read(from: &buf)
        )
        
        case 5: return .emergencyReceived(fromNode: try FfiConverterUInt32.read(from: &buf)
        )
        
        case 6: return .ackReceived(fromNode: try FfiConverterUInt32.read(from: &buf)
        )
        
        case 7: return .documentSynced(fromNode: try FfiConverterUInt32.read(from: &buf), totalCount: try FfiConverterUInt64.read(from: &buf)
        )
        
        case 8: return .meshStateChanged(peerCount: try FfiConverterUInt32.read(from: &buf), connectedCount: try FfiConverterUInt32.read(from: &buf)
        )
        
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: MeshEvent, into buf: inout [UInt8]) {
        switch value {
        
        
        case let .peerDiscovered(peer):
            writeInt(&buf, Int32(1))
            FfiConverterTypeMeshPeer.write(peer, into: &buf)
            
        
        case let .peerConnected(nodeId):
            writeInt(&buf, Int32(2))
            FfiConverterUInt32.write(nodeId, into: &buf)
            
        
        case let .peerDisconnected(nodeId,reason):
            writeInt(&buf, Int32(3))
            FfiConverterUInt32.write(nodeId, into: &buf)
            FfiConverterTypeMeshDisconnectReason.write(reason, into: &buf)
            
        
        case let .peerLost(nodeId):
            writeInt(&buf, Int32(4))
            FfiConverterUInt32.write(nodeId, into: &buf)
            
        
        case let .emergencyReceived(fromNode):
            writeInt(&buf, Int32(5))
            FfiConverterUInt32.write(fromNode, into: &buf)
            
        
        case let .ackReceived(fromNode):
            writeInt(&buf, Int32(6))
            FfiConverterUInt32.write(fromNode, into: &buf)
            
        
        case let .documentSynced(fromNode,totalCount):
            writeInt(&buf, Int32(7))
            FfiConverterUInt32.write(fromNode, into: &buf)
            FfiConverterUInt64.write(totalCount, into: &buf)
            
        
        case let .meshStateChanged(peerCount,connectedCount):
            writeInt(&buf, Int32(8))
            FfiConverterUInt32.write(peerCount, into: &buf)
            FfiConverterUInt32.write(connectedCount, into: &buf)
            
        }
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshEvent_lift(_ buf: RustBuffer) throws -> MeshEvent {
    return try FfiConverterTypeMeshEvent.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshEvent_lower(_ value: MeshEvent) -> RustBuffer {
    return FfiConverterTypeMeshEvent.lower(value)
}



extension MeshEvent: Equatable, Hashable {}



// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
 * Peripheral type
 */

public enum MeshPeripheralType {
    
    case unknown
    case soldierSensor
    case fixedSensor
    case relay
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeMeshPeripheralType: FfiConverterRustBuffer {
    typealias SwiftType = MeshPeripheralType

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> MeshPeripheralType {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        
        case 1: return .unknown
        
        case 2: return .soldierSensor
        
        case 3: return .fixedSensor
        
        case 4: return .relay
        
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: MeshPeripheralType, into buf: inout [UInt8]) {
        switch value {
        
        
        case .unknown:
            writeInt(&buf, Int32(1))
        
        
        case .soldierSensor:
            writeInt(&buf, Int32(2))
        
        
        case .fixedSensor:
            writeInt(&buf, Int32(3))
        
        
        case .relay:
            writeInt(&buf, Int32(4))
        
        }
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshPeripheralType_lift(_ buf: RustBuffer) throws -> MeshPeripheralType {
    return try FfiConverterTypeMeshPeripheralType.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshPeripheralType_lower(_ value: MeshPeripheralType) -> RustBuffer {
    return FfiConverterTypeMeshPeripheralType.lower(value)
}



extension MeshPeripheralType: Equatable, Hashable {}



// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/**
 * Signal strength category
 */

public enum MeshSignalStrength {
    
    case excellent
    case good
    case fair
    case weak
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeMeshSignalStrength: FfiConverterRustBuffer {
    typealias SwiftType = MeshSignalStrength

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> MeshSignalStrength {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        
        case 1: return .excellent
        
        case 2: return .good
        
        case 3: return .fair
        
        case 4: return .weak
        
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: MeshSignalStrength, into buf: inout [UInt8]) {
        switch value {
        
        
        case .excellent:
            writeInt(&buf, Int32(1))
        
        
        case .good:
            writeInt(&buf, Int32(2))
        
        
        case .fair:
            writeInt(&buf, Int32(3))
        
        
        case .weak:
            writeInt(&buf, Int32(4))
        
        }
    }
}


#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshSignalStrength_lift(_ buf: RustBuffer) throws -> MeshSignalStrength {
    return try FfiConverterTypeMeshSignalStrength.lift(buf)
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeMeshSignalStrength_lower(_ value: MeshSignalStrength) -> RustBuffer {
    return FfiConverterTypeMeshSignalStrength.lower(value)
}



extension MeshSignalStrength: Equatable, Hashable {}






/**
 * Callback interface for connection events
 */
public protocol ConnectionCallback : AnyObject {
    
    func onConnected(peerId: UInt32, info: ConnectionInfo) 
    
    func onDisconnected(peerId: UInt32, reason: String) 
    
    func onConnectionFailed(identifier: String, error: String) 
    
}

// Magic number for the Rust proxy to call using the same mechanism as every other method,
// to free the callback once it's dropped by Rust.
private let IDX_CALLBACK_FREE: Int32 = 0
// Callback return codes
private let UNIFFI_CALLBACK_SUCCESS: Int32 = 0
private let UNIFFI_CALLBACK_ERROR: Int32 = 1
private let UNIFFI_CALLBACK_UNEXPECTED_ERROR: Int32 = 2

// Put the implementation in a struct so we don't pollute the top-level namespace
fileprivate struct UniffiCallbackInterfaceConnectionCallback {

    // Create the VTable using a series of closures.
    // Swift automatically converts these into C callback functions.
    static var vtable: UniffiVTableCallbackInterfaceConnectionCallback = UniffiVTableCallbackInterfaceConnectionCallback(
        onConnected: { (
            uniffiHandle: UInt64,
            peerId: UInt32,
            info: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceConnectionCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onConnected(
                     peerId: try FfiConverterUInt32.lift(peerId),
                     info: try FfiConverterTypeConnectionInfo.lift(info)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        onDisconnected: { (
            uniffiHandle: UInt64,
            peerId: UInt32,
            reason: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceConnectionCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onDisconnected(
                     peerId: try FfiConverterUInt32.lift(peerId),
                     reason: try FfiConverterString.lift(reason)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        onConnectionFailed: { (
            uniffiHandle: UInt64,
            identifier: RustBuffer,
            error: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceConnectionCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onConnectionFailed(
                     identifier: try FfiConverterString.lift(identifier),
                     error: try FfiConverterString.lift(error)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        uniffiFree: { (uniffiHandle: UInt64) -> () in
            let result = try? FfiConverterCallbackInterfaceConnectionCallback.handleMap.remove(handle: uniffiHandle)
            if result == nil {
                print("Uniffi callback interface ConnectionCallback: handle missing in uniffiFree")
            }
        }
    )
}

private func uniffiCallbackInitConnectionCallback() {
    uniffi_peat_apple_ffi_fn_init_callback_vtable_connectioncallback(&UniffiCallbackInterfaceConnectionCallback.vtable)
}

// FfiConverter protocol for callback interfaces
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterCallbackInterfaceConnectionCallback {
    fileprivate static var handleMap = UniffiHandleMap<ConnectionCallback>()
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
extension FfiConverterCallbackInterfaceConnectionCallback : FfiConverter {
    typealias SwiftType = ConnectionCallback
    typealias FfiType = UInt64

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lift(_ handle: UInt64) throws -> SwiftType {
        try handleMap.get(handle: handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        let handle: UInt64 = try readInt(&buf)
        return try lift(handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lower(_ v: SwiftType) -> UInt64 {
        return handleMap.insert(obj: v)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(v))
    }
}




/**
 * Callback interface for data reception
 */
public protocol DataCallback : AnyObject {
    
    func onDataReceived(peerId: UInt32, data: Data) 
    
}



// Put the implementation in a struct so we don't pollute the top-level namespace
fileprivate struct UniffiCallbackInterfaceDataCallback {

    // Create the VTable using a series of closures.
    // Swift automatically converts these into C callback functions.
    static var vtable: UniffiVTableCallbackInterfaceDataCallback = UniffiVTableCallbackInterfaceDataCallback(
        onDataReceived: { (
            uniffiHandle: UInt64,
            peerId: UInt32,
            data: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceDataCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onDataReceived(
                     peerId: try FfiConverterUInt32.lift(peerId),
                     data: try FfiConverterData.lift(data)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        uniffiFree: { (uniffiHandle: UInt64) -> () in
            let result = try? FfiConverterCallbackInterfaceDataCallback.handleMap.remove(handle: uniffiHandle)
            if result == nil {
                print("Uniffi callback interface DataCallback: handle missing in uniffiFree")
            }
        }
    )
}

private func uniffiCallbackInitDataCallback() {
    uniffi_peat_apple_ffi_fn_init_callback_vtable_datacallback(&UniffiCallbackInterfaceDataCallback.vtable)
}

// FfiConverter protocol for callback interfaces
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterCallbackInterfaceDataCallback {
    fileprivate static var handleMap = UniffiHandleMap<DataCallback>()
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
extension FfiConverterCallbackInterfaceDataCallback : FfiConverter {
    typealias SwiftType = DataCallback
    typealias FfiType = UInt64

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lift(_ handle: UInt64) throws -> SwiftType {
        try handleMap.get(handle: handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        let handle: UInt64 = try readInt(&buf)
        return try lift(handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lower(_ v: SwiftType) -> UInt64 {
        return handleMap.insert(obj: v)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(v))
    }
}




/**
 * Callback interface for discovery events
 */
public protocol DiscoveryCallback : AnyObject {
    
    func onPeerDiscovered(peer: DiscoveredPeer) 
    
    func onPeerLost(identifier: String) 
    
}



// Put the implementation in a struct so we don't pollute the top-level namespace
fileprivate struct UniffiCallbackInterfaceDiscoveryCallback {

    // Create the VTable using a series of closures.
    // Swift automatically converts these into C callback functions.
    static var vtable: UniffiVTableCallbackInterfaceDiscoveryCallback = UniffiVTableCallbackInterfaceDiscoveryCallback(
        onPeerDiscovered: { (
            uniffiHandle: UInt64,
            peer: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceDiscoveryCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onPeerDiscovered(
                     peer: try FfiConverterTypeDiscoveredPeer.lift(peer)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        onPeerLost: { (
            uniffiHandle: UInt64,
            identifier: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceDiscoveryCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onPeerLost(
                     identifier: try FfiConverterString.lift(identifier)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        uniffiFree: { (uniffiHandle: UInt64) -> () in
            let result = try? FfiConverterCallbackInterfaceDiscoveryCallback.handleMap.remove(handle: uniffiHandle)
            if result == nil {
                print("Uniffi callback interface DiscoveryCallback: handle missing in uniffiFree")
            }
        }
    )
}

private func uniffiCallbackInitDiscoveryCallback() {
    uniffi_peat_apple_ffi_fn_init_callback_vtable_discoverycallback(&UniffiCallbackInterfaceDiscoveryCallback.vtable)
}

// FfiConverter protocol for callback interfaces
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterCallbackInterfaceDiscoveryCallback {
    fileprivate static var handleMap = UniffiHandleMap<DiscoveryCallback>()
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
extension FfiConverterCallbackInterfaceDiscoveryCallback : FfiConverter {
    typealias SwiftType = DiscoveryCallback
    typealias FfiType = UInt64

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lift(_ handle: UInt64) throws -> SwiftType {
        try handleMap.get(handle: handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        let handle: UInt64 = try readInt(&buf)
        return try lift(handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lower(_ v: SwiftType) -> UInt64 {
        return handleMap.insert(obj: v)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(v))
    }
}




/**
 * Callback interface for mesh events
 */
public protocol MeshEventCallback : AnyObject {
    
    func onEvent(event: MeshEvent) 
    
}



// Put the implementation in a struct so we don't pollute the top-level namespace
fileprivate struct UniffiCallbackInterfaceMeshEventCallback {

    // Create the VTable using a series of closures.
    // Swift automatically converts these into C callback functions.
    static var vtable: UniffiVTableCallbackInterfaceMeshEventCallback = UniffiVTableCallbackInterfaceMeshEventCallback(
        onEvent: { (
            uniffiHandle: UInt64,
            event: RustBuffer,
            uniffiOutReturn: UnsafeMutableRawPointer,
            uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
        ) in
            let makeCall = {
                () throws -> () in
                guard let uniffiObj = try? FfiConverterCallbackInterfaceMeshEventCallback.handleMap.get(handle: uniffiHandle) else {
                    throw UniffiInternalError.unexpectedStaleHandle
                }
                return uniffiObj.onEvent(
                     event: try FfiConverterTypeMeshEvent.lift(event)
                )
            }

            
            let writeReturn = { () }
            uniffiTraitInterfaceCall(
                callStatus: uniffiCallStatus,
                makeCall: makeCall,
                writeReturn: writeReturn
            )
        },
        uniffiFree: { (uniffiHandle: UInt64) -> () in
            let result = try? FfiConverterCallbackInterfaceMeshEventCallback.handleMap.remove(handle: uniffiHandle)
            if result == nil {
                print("Uniffi callback interface MeshEventCallback: handle missing in uniffiFree")
            }
        }
    )
}

private func uniffiCallbackInitMeshEventCallback() {
    uniffi_peat_apple_ffi_fn_init_callback_vtable_mesheventcallback(&UniffiCallbackInterfaceMeshEventCallback.vtable)
}

// FfiConverter protocol for callback interfaces
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterCallbackInterfaceMeshEventCallback {
    fileprivate static var handleMap = UniffiHandleMap<MeshEventCallback>()
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
extension FfiConverterCallbackInterfaceMeshEventCallback : FfiConverter {
    typealias SwiftType = MeshEventCallback
    typealias FfiType = UInt64

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lift(_ handle: UInt64) throws -> SwiftType {
        try handleMap.get(handle: handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        let handle: UInt64 = try readInt(&buf)
        return try lift(handle)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func lower(_ v: SwiftType) -> UInt64 {
        return handleMap.insert(obj: v)
    }

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
    public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(v))
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionInt8: FfiConverterRustBuffer {
    typealias SwiftType = Int8?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterInt8.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterInt8.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionUInt32: FfiConverterRustBuffer {
    typealias SwiftType = UInt32?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterUInt32.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterUInt32.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionUInt64: FfiConverterRustBuffer {
    typealias SwiftType = UInt64?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterUInt64.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterUInt64.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
    typealias SwiftType = String?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterString.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterString.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionData: FfiConverterRustBuffer {
    typealias SwiftType = Data?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterData.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterData.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionTypeConnectionInfo: FfiConverterRustBuffer {
    typealias SwiftType = ConnectionInfo?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeConnectionInfo.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeConnectionInfo.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionTypeDataReceivedResult: FfiConverterRustBuffer {
    typealias SwiftType = DataReceivedResult?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeDataReceivedResult.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeDataReceivedResult.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionTypeEmergencyStatus: FfiConverterRustBuffer {
    typealias SwiftType = EmergencyStatus?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeEmergencyStatus.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeEmergencyStatus.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionTypeMeshPeer: FfiConverterRustBuffer {
    typealias SwiftType = MeshPeer?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeMeshPeer.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeMeshPeer.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterOptionTypeParsedDeviceName: FfiConverterRustBuffer {
    typealias SwiftType = ParsedDeviceName?

    public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeParsedDeviceName.write(value, into: &buf)
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeParsedDeviceName.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterSequenceUInt32: FfiConverterRustBuffer {
    typealias SwiftType = [UInt32]

    public static func write(_ value: [UInt32], into buf: inout [UInt8]) {
        let len = Int32(value.count)
        writeInt(&buf, len)
        for item in value {
            FfiConverterUInt32.write(item, into: &buf)
        }
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [UInt32] {
        let len: Int32 = try readInt(&buf)
        var seq = [UInt32]()
        seq.reserveCapacity(Int(len))
        for _ in 0 ..< len {
            seq.append(try FfiConverterUInt32.read(from: &buf))
        }
        return seq
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterSequenceTypeConnectionInfo: FfiConverterRustBuffer {
    typealias SwiftType = [ConnectionInfo]

    public static func write(_ value: [ConnectionInfo], into buf: inout [UInt8]) {
        let len = Int32(value.count)
        writeInt(&buf, len)
        for item in value {
            FfiConverterTypeConnectionInfo.write(item, into: &buf)
        }
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ConnectionInfo] {
        let len: Int32 = try readInt(&buf)
        var seq = [ConnectionInfo]()
        seq.reserveCapacity(Int(len))
        for _ in 0 ..< len {
            seq.append(try FfiConverterTypeConnectionInfo.read(from: &buf))
        }
        return seq
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterSequenceTypeDiscoveredPeer: FfiConverterRustBuffer {
    typealias SwiftType = [DiscoveredPeer]

    public static func write(_ value: [DiscoveredPeer], into buf: inout [UInt8]) {
        let len = Int32(value.count)
        writeInt(&buf, len)
        for item in value {
            FfiConverterTypeDiscoveredPeer.write(item, into: &buf)
        }
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [DiscoveredPeer] {
        let len: Int32 = try readInt(&buf)
        var seq = [DiscoveredPeer]()
        seq.reserveCapacity(Int(len))
        for _ in 0 ..< len {
            seq.append(try FfiConverterTypeDiscoveredPeer.read(from: &buf))
        }
        return seq
    }
}

#if swift(>=5.8)
@_documentation(visibility: private)
#endif
fileprivate struct FfiConverterSequenceTypeMeshPeer: FfiConverterRustBuffer {
    typealias SwiftType = [MeshPeer]

    public static func write(_ value: [MeshPeer], into buf: inout [UInt8]) {
        let len = Int32(value.count)
        writeInt(&buf, len)
        for item in value {
            FfiConverterTypeMeshPeer.write(item, into: &buf)
        }
    }

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [MeshPeer] {
        let len: Int32 = try readInt(&buf)
        var seq = [MeshPeer]()
        seq.reserveCapacity(Int(len))
        for _ in 0 ..< len {
            seq.append(try FfiConverterTypeMeshPeer.read(from: &buf))
        }
        return seq
    }
}
/**
 * Generate an Peat device name for advertising
 */
public func generatePeatDeviceName(meshId: String, nodeId: UInt32) -> String {
    return try!  FfiConverterString.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_func_generate_peat_device_name(
        FfiConverterString.lower(meshId),
        FfiConverterUInt32.lower(nodeId),$0
    )
})
}
/**
 * Get the default mesh ID used for demos
 */
public func getDefaultMeshId() -> String {
    return try!  FfiConverterString.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_func_get_default_mesh_id($0
    )
})
}
/**
 * Initialize logging for the library
 */
public func initLogging() {try! rustCall() {
    uniffi_peat_apple_ffi_fn_func_init_logging($0
    )
}
}
/**
 * Check if a device matches a specific mesh
 *
 * Returns true if the device has the same mesh ID, or if the device
 * has no mesh ID (legacy format - backwards compatible)
 */
public func matchesMesh(ourMeshId: String, deviceMeshId: String?) -> Bool {
    return try!  FfiConverterBool.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_func_matches_mesh(
        FfiConverterString.lower(ourMeshId),
        FfiConverterOptionString.lower(deviceMeshId),$0
    )
})
}
/**
 * Parse an Peat device name to extract mesh ID and node ID
 *
 * Supports both formats:
 * - New: `PEAT_<MESH_ID>-<NODE_ID>` (e.g., "PEAT_DEMO-12345678")
 * - Legacy: `PEAT-<NODE_ID>` (e.g., "PEAT-12345678")
 */
public func parsePeatDeviceName(name: String) -> ParsedDeviceName? {
    return try!  FfiConverterOptionTypeParsedDeviceName.lift(try! rustCall() {
    uniffi_peat_apple_ffi_fn_func_parse_peat_device_name(
        FfiConverterString.lower(name),$0
    )
})
}

private enum InitializationResult {
    case ok
    case contractVersionMismatch
    case apiChecksumMismatch
}
// Use a global variable to perform the versioning checks. Swift ensures that
// the code inside is only computed once.
private var initializationResult: InitializationResult = {
    // Get the bindings contract version from our ComponentInterface
    let bindings_contract_version = 26
    // Get the scaffolding contract version by calling the into the dylib
    let scaffolding_contract_version = ffi_peat_apple_ffi_uniffi_contract_version()
    if bindings_contract_version != scaffolding_contract_version {
        return InitializationResult.contractVersionMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_func_generate_peat_device_name() != 3701) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_func_get_default_mesh_id() != 45532) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_func_init_logging() != 59193) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_func_matches_mesh() != 37344) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_func_parse_peat_device_name() != 29336) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_add_mock_peer() != 56256) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_broadcast_data() != 42306) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_connect() != 10197) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_device_matches_mesh() != 21339) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_disconnect() != 44937) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_disconnect_all() != 14015) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_bluetooth_state() != 36371) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_connection() != 8323) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_connections() != 16513) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_device_name() != 47993) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_discovered_peers() != 61087) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_mesh_id() != 39785) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_node_id() != 33530) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_get_sync_stats() != 3276) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_is_advertising() != 50538) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_is_discovering() != 38973) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_is_running() != 35566) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_process_events() != 39269) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_send_data() != 47753) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_set_connection_callback() != 51469) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_set_data_callback() != 48111) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_set_discovery_callback() != 28261) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_start() != 14040) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_start_advertising() != 32953) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_start_discovery() != 32256) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_stop() != 18732) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_stop_advertising() != 41924) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_stop_discovery() != 6648) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hiveadapter_trigger_sync() != 21274) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_ack_emergency() != 9227) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_add_observer() != 7641) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_all_peers_acked() != 28880) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_build_document() != 52541) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_clear_emergency() != 13833) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_clear_event() != 65017) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_connected_count() != 23818) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_device_name() != 11978) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_get_connected_peers() != 62169) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_get_emergency_status() != 9143) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_get_peers() != 61043) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_has_active_emergency() != 46969) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_has_peer_acked() != 49435) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_is_ack_active() != 56292) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_is_emergency_active() != 15447) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_matches_mesh() != 20651) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_mesh_id() != 61676) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_node_id() != 35762) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_on_ble_connected() != 47658) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_on_ble_data() != 26913) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_on_ble_data_received() != 14592) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_on_ble_disconnected() != 41090) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_on_ble_discovered() != 18383) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_on_incoming_connection() != 45906) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_peer_count() != 29710) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_send_ack() != 50203) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_send_emergency() != 49673) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_start_emergency() != 4070) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_start_emergency_with_known_peers() != 56932) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_tick() != 22459) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_hivemeshwrapper_total_count() != 36231) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_constructor_hiveadapter_new() != 389) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_constructor_hiveadapter_with_mesh_id() != 63879) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_constructor_hivemeshwrapper_new() != 54979) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_constructor_hivemeshwrapper_with_defaults() != 59396) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_connectioncallback_on_connected() != 25180) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_connectioncallback_on_disconnected() != 40345) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_connectioncallback_on_connection_failed() != 15050) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_datacallback_on_data_received() != 32260) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_discoverycallback_on_peer_discovered() != 30617) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_discoverycallback_on_peer_lost() != 10655) {
        return InitializationResult.apiChecksumMismatch
    }
    if (uniffi_peat_apple_ffi_checksum_method_mesheventcallback_on_event() != 2323) {
        return InitializationResult.apiChecksumMismatch
    }

    uniffiCallbackInitConnectionCallback()
    uniffiCallbackInitDataCallback()
    uniffiCallbackInitDiscoveryCallback()
    uniffiCallbackInitMeshEventCallback()
    return InitializationResult.ok
}()

private func uniffiEnsureInitialized() {
    switch initializationResult {
    case .ok:
        break
    case .contractVersionMismatch:
        fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
    case .apiChecksumMismatch:
        fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
    }
}

// swiftlint:enable all