// 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(CooklangImportFFI)
import CooklangImportFFI
#endif
private 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_cooklang_import_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_cooklang_import_rustbuffer_free(self, $0) }
}
}
private 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.
private 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
private 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.
private 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
private func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> [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.
private func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
return try Float(bitPattern: readInt(&reader))
}
/// Reads a float at the current offset.
private func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
return try Double(bitPattern: readInt(&reader))
}
/// Indicates if the offset has reached the end of the buffer.
private 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.
private func createWriter() -> [UInt8] {
return []
}
private func writeBytes<S: Sequence>(_ writer: inout [UInt8], _ byteArr: S) where 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!
private func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
var value = value.bigEndian
withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
}
private func writeFloat(_ writer: inout [UInt8], _ value: Float) {
writeInt(&writer, value.bitPattern)
}
private 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.
private 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.
private 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.
private 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.
private enum UniffiInternalError: LocalizedError {
case bufferOverflow
case incompleteData
case unexpectedOptionalTag
case unexpectedEnumCase
case unexpectedNullPointer
case unexpectedRustCallStatusCode
case unexpectedRustCallError
case unexpectedStaleHandle
case rustPanic(_ message: String)
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
}
}
}
private extension NSLock {
func withLock<T>(f: () throws -> T) rethrows -> T {
lock()
defer { self.unlock() }
return try f()
}
}
private let CALL_SUCCESS: Int8 = 0
private let CALL_ERROR: Int8 = 1
private let CALL_UNEXPECTED_ERROR: Int8 = 2
private let CALL_CANCELLED: Int8 = 3
private extension RustCallStatus {
init() {
self.init(
code: CALL_SUCCESS,
errorBuf: RustBuffer(
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()
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 try UniffiInternalError.rustPanic(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) -> Void
) {
do {
try writeReturn(makeCall())
} catch {
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) -> Void,
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))
}
}
private 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 {
map.count
}
}
// Public interface members begin here.
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
private struct FfiConverterUInt64: FfiConverterPrimitive {
typealias FfiType = UInt64
typealias SwiftType = UInt64
static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 {
return try lift(readInt(&buf))
}
static func write(_ value: SwiftType, into buf: inout [UInt8]) {
writeInt(&buf, lower(value))
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
private struct FfiConverterBool: FfiConverter {
typealias FfiType = Int8
typealias SwiftType = Bool
static func lift(_ value: Int8) throws -> Bool {
return value != 0
}
static func lower(_ value: Bool) -> Int8 {
return value ? 1 : 0
}
static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
return try lift(readInt(&buf))
}
static func write(_ value: Bool, into buf: inout [UInt8]) {
writeInt(&buf, lower(value))
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
private struct FfiConverterString: FfiConverter {
typealias SwiftType = String
typealias FfiType = RustBuffer
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)!
}
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)
}
}
}
static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
let len: Int32 = try readInt(&buf)
return try String(bytes: readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
}
static func write(_ value: String, into buf: inout [UInt8]) {
let len = Int32(value.utf8.count)
writeInt(&buf, len)
writeBytes(&buf, value.utf8)
}
}
/**
* Configuration for importing recipes
*/
public struct FfiImportConfig {
/**
* Optional LLM provider (uses default if not specified)
*/
public let provider: FfiLlmProvider?
/**
* Optional API key (uses environment variable if not specified)
*/
public let apiKey: String?
/**
* Optional model name (uses provider default if not specified)
*/
public let model: String?
/**
* Optional timeout in seconds (uses default if not specified)
*/
public let timeoutSeconds: UInt64?
/**
* If true, only extract recipe without converting to Cooklang
*/
public let extractOnly: Bool
/// Default memberwise initializers are never public by default, so we
/// declare one manually.
public init(
/*
* Optional LLM provider (uses default if not specified)
*/ provider: FfiLlmProvider?,
/*
* Optional API key (uses environment variable if not specified)
*/ apiKey: String?,
/*
* Optional model name (uses provider default if not specified)
*/ model: String?,
/*
* Optional timeout in seconds (uses default if not specified)
*/ timeoutSeconds: UInt64?,
/*
* If true, only extract recipe without converting to Cooklang
*/ extractOnly: Bool
) {
self.provider = provider
self.apiKey = apiKey
self.model = model
self.timeoutSeconds = timeoutSeconds
self.extractOnly = extractOnly
}
}
extension FfiImportConfig: Equatable, Hashable {
public static func == (lhs: FfiImportConfig, rhs: FfiImportConfig) -> Bool {
if lhs.provider != rhs.provider {
return false
}
if lhs.apiKey != rhs.apiKey {
return false
}
if lhs.model != rhs.model {
return false
}
if lhs.timeoutSeconds != rhs.timeoutSeconds {
return false
}
if lhs.extractOnly != rhs.extractOnly {
return false
}
return true
}
public func hash(into hasher: inout Hasher) {
hasher.combine(provider)
hasher.combine(apiKey)
hasher.combine(model)
hasher.combine(timeoutSeconds)
hasher.combine(extractOnly)
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiImportConfig: FfiConverterRustBuffer {
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiImportConfig {
return
try FfiImportConfig(
provider: FfiConverterOptionTypeFfiLlmProvider.read(from: &buf),
apiKey: FfiConverterOptionString.read(from: &buf),
model: FfiConverterOptionString.read(from: &buf),
timeoutSeconds: FfiConverterOptionUInt64.read(from: &buf),
extractOnly: FfiConverterBool.read(from: &buf)
)
}
public static func write(_ value: FfiImportConfig, into buf: inout [UInt8]) {
FfiConverterOptionTypeFfiLlmProvider.write(value.provider, into: &buf)
FfiConverterOptionString.write(value.apiKey, into: &buf)
FfiConverterOptionString.write(value.model, into: &buf)
FfiConverterOptionUInt64.write(value.timeoutSeconds, into: &buf)
FfiConverterBool.write(value.extractOnly, into: &buf)
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportConfig_lift(_ buf: RustBuffer) throws -> FfiImportConfig {
return try FfiConverterTypeFfiImportConfig.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportConfig_lower(_ value: FfiImportConfig) -> RustBuffer {
return FfiConverterTypeFfiImportConfig.lower(value)
}
/**
* FFI-compatible recipe components structure
*/
public struct FfiRecipeComponents {
/**
* Recipe text (ingredients + instructions)
*/
public let text: String
/**
* YAML-formatted metadata (without --- delimiters)
*/
public let metadata: String
/**
* Recipe name/title
*/
public let name: String
/// Default memberwise initializers are never public by default, so we
/// declare one manually.
public init(
/*
* Recipe text (ingredients + instructions)
*/ text: String,
/*
* YAML-formatted metadata (without --- delimiters)
*/ metadata: String,
/*
* Recipe name/title
*/ name: String
) {
self.text = text
self.metadata = metadata
self.name = name
}
}
extension FfiRecipeComponents: Equatable, Hashable {
public static func == (lhs: FfiRecipeComponents, rhs: FfiRecipeComponents) -> Bool {
if lhs.text != rhs.text {
return false
}
if lhs.metadata != rhs.metadata {
return false
}
if lhs.name != rhs.name {
return false
}
return true
}
public func hash(into hasher: inout Hasher) {
hasher.combine(text)
hasher.combine(metadata)
hasher.combine(name)
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiRecipeComponents: FfiConverterRustBuffer {
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiRecipeComponents {
return
try FfiRecipeComponents(
text: FfiConverterString.read(from: &buf),
metadata: FfiConverterString.read(from: &buf),
name: FfiConverterString.read(from: &buf)
)
}
public static func write(_ value: FfiRecipeComponents, into buf: inout [UInt8]) {
FfiConverterString.write(value.text, into: &buf)
FfiConverterString.write(value.metadata, into: &buf)
FfiConverterString.write(value.name, into: &buf)
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiRecipeComponents_lift(_ buf: RustBuffer) throws -> FfiRecipeComponents {
return try FfiConverterTypeFfiRecipeComponents.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiRecipeComponents_lower(_ value: FfiRecipeComponents) -> RustBuffer {
return FfiConverterTypeFfiRecipeComponents.lower(value)
}
/**
* FFI-compatible error type
*/
public enum FfiImportError {
/**
* Failed to fetch recipe from URL
*/
case FetchError(reason: String)
/**
* Failed to parse recipe from webpage
*/
case ParseError(reason: String)
/**
* No extractor could successfully parse the recipe
*/
case NoExtractorMatched(reason: String)
/**
* Failed to convert recipe to Cooklang format
*/
case ConversionError(reason: String)
/**
* Invalid input provided
*/
case InvalidInput(reason: String)
/**
* Builder configuration error
*/
case BuilderError(reason: String)
/**
* Configuration error
*/
case ConfigError(reason: String)
/**
* Runtime error (tokio)
*/
case RuntimeError(reason: String)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiImportError: FfiConverterRustBuffer {
typealias SwiftType = FfiImportError
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiImportError {
let variant: Int32 = try readInt(&buf)
switch variant {
case 1: return try .FetchError(
reason: FfiConverterString.read(from: &buf)
)
case 2: return try .ParseError(
reason: FfiConverterString.read(from: &buf)
)
case 3: return try .NoExtractorMatched(
reason: FfiConverterString.read(from: &buf)
)
case 4: return try .ConversionError(
reason: FfiConverterString.read(from: &buf)
)
case 5: return try .InvalidInput(
reason: FfiConverterString.read(from: &buf)
)
case 6: return try .BuilderError(
reason: FfiConverterString.read(from: &buf)
)
case 7: return try .ConfigError(
reason: FfiConverterString.read(from: &buf)
)
case 8: return try .RuntimeError(
reason: FfiConverterString.read(from: &buf)
)
default: throw UniffiInternalError.unexpectedEnumCase
}
}
public static func write(_ value: FfiImportError, into buf: inout [UInt8]) {
switch value {
case let .FetchError(reason):
writeInt(&buf, Int32(1))
FfiConverterString.write(reason, into: &buf)
case let .ParseError(reason):
writeInt(&buf, Int32(2))
FfiConverterString.write(reason, into: &buf)
case let .NoExtractorMatched(reason):
writeInt(&buf, Int32(3))
FfiConverterString.write(reason, into: &buf)
case let .ConversionError(reason):
writeInt(&buf, Int32(4))
FfiConverterString.write(reason, into: &buf)
case let .InvalidInput(reason):
writeInt(&buf, Int32(5))
FfiConverterString.write(reason, into: &buf)
case let .BuilderError(reason):
writeInt(&buf, Int32(6))
FfiConverterString.write(reason, into: &buf)
case let .ConfigError(reason):
writeInt(&buf, Int32(7))
FfiConverterString.write(reason, into: &buf)
case let .RuntimeError(reason):
writeInt(&buf, Int32(8))
FfiConverterString.write(reason, into: &buf)
}
}
}
extension FfiImportError: Equatable, Hashable {}
extension FfiImportError: 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.
/*
* FFI-compatible import result
*/
public enum FfiImportResult {
/**
* Recipe converted to Cooklang format
*/
case cooklang(content: String)
/**
* Recipe components extracted but not converted
*/
case components(components: FfiRecipeComponents)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiImportResult: FfiConverterRustBuffer {
typealias SwiftType = FfiImportResult
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiImportResult {
let variant: Int32 = try readInt(&buf)
switch variant {
case 1: return try .cooklang(content: FfiConverterString.read(from: &buf))
case 2: return try .components(components: FfiConverterTypeFfiRecipeComponents.read(from: &buf))
default: throw UniffiInternalError.unexpectedEnumCase
}
}
public static func write(_ value: FfiImportResult, into buf: inout [UInt8]) {
switch value {
case let .cooklang(content):
writeInt(&buf, Int32(1))
FfiConverterString.write(content, into: &buf)
case let .components(components):
writeInt(&buf, Int32(2))
FfiConverterTypeFfiRecipeComponents.write(components, into: &buf)
}
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportResult_lift(_ buf: RustBuffer) throws -> FfiImportResult {
return try FfiConverterTypeFfiImportResult.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportResult_lower(_ value: FfiImportResult) -> RustBuffer {
return FfiConverterTypeFfiImportResult.lower(value)
}
extension FfiImportResult: Equatable, Hashable {}
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/*
* FFI-compatible LLM provider enum
*/
public enum FfiLlmProvider {
case openAi
case anthropic
case google
case azureOpenAi
case ollama
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiLlmProvider: FfiConverterRustBuffer {
typealias SwiftType = FfiLlmProvider
public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiLlmProvider {
let variant: Int32 = try readInt(&buf)
switch variant {
case 1: return .openAi
case 2: return .anthropic
case 3: return .google
case 4: return .azureOpenAi
case 5: return .ollama
default: throw UniffiInternalError.unexpectedEnumCase
}
}
public static func write(_ value: FfiLlmProvider, into buf: inout [UInt8]) {
switch value {
case .openAi:
writeInt(&buf, Int32(1))
case .anthropic:
writeInt(&buf, Int32(2))
case .google:
writeInt(&buf, Int32(3))
case .azureOpenAi:
writeInt(&buf, Int32(4))
case .ollama:
writeInt(&buf, Int32(5))
}
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiLlmProvider_lift(_ buf: RustBuffer) throws -> FfiLlmProvider {
return try FfiConverterTypeFfiLlmProvider.lift(buf)
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiLlmProvider_lower(_ value: FfiLlmProvider) -> RustBuffer {
return FfiConverterTypeFfiLlmProvider.lower(value)
}
extension FfiLlmProvider: Equatable, Hashable {}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
private struct FfiConverterOptionUInt64: FfiConverterRustBuffer {
typealias SwiftType = UInt64?
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)
}
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
private struct FfiConverterOptionString: FfiConverterRustBuffer {
typealias SwiftType = String?
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)
}
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
private struct FfiConverterOptionTypeFfiImportConfig: FfiConverterRustBuffer {
typealias SwiftType = FfiImportConfig?
static func write(_ value: SwiftType, into buf: inout [UInt8]) {
guard let value = value else {
writeInt(&buf, Int8(0))
return
}
writeInt(&buf, Int8(1))
FfiConverterTypeFfiImportConfig.write(value, into: &buf)
}
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 FfiConverterTypeFfiImportConfig.read(from: &buf)
default: throw UniffiInternalError.unexpectedOptionalTag
}
}
}
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
private struct FfiConverterOptionTypeFfiLlmProvider: FfiConverterRustBuffer {
typealias SwiftType = FfiLlmProvider?
static func write(_ value: SwiftType, into buf: inout [UInt8]) {
guard let value = value else {
writeInt(&buf, Int8(0))
return
}
writeInt(&buf, Int8(1))
FfiConverterTypeFfiLlmProvider.write(value, into: &buf)
}
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 FfiConverterTypeFfiLlmProvider.read(from: &buf)
default: throw UniffiInternalError.unexpectedOptionalTag
}
}
}
/**
* Convert an image to Cooklang format using OCR
*
* # Arguments
* * `image_path` - Path to the image file
* * `config` - Optional configuration for the conversion
*
* # Returns
* A string containing the recipe in Cooklang format
*/
public func convertImageToCooklang(imagePath: String, config: FfiImportConfig?) throws -> String {
return try FfiConverterString.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
uniffi_cooklang_import_fn_func_convert_image_to_cooklang(
FfiConverterString.lower(imagePath),
FfiConverterOptionTypeFfiImportConfig.lower(config), $0
)
})
}
/**
* Convert plain text to Cooklang format
*
* # Arguments
* * `text` - The recipe text in plain format
* * `config` - Optional configuration for the conversion
*
* # Returns
* A string containing the recipe in Cooklang format
*/
public func convertTextToCooklang(text: String, config: FfiImportConfig?) throws -> String {
return try FfiConverterString.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
uniffi_cooklang_import_fn_func_convert_text_to_cooklang(
FfiConverterString.lower(text),
FfiConverterOptionTypeFfiImportConfig.lower(config), $0
)
})
}
/**
* Extract recipe components from a URL without converting to Cooklang format
*
* # Arguments
* * `url` - The URL of the recipe webpage
* * `timeout_seconds` - Optional timeout in seconds
*
* # Returns
* An `FfiRecipeComponents` struct containing the extracted recipe data
*/
public func extractRecipeFromUrl(url: String, timeoutSeconds: UInt64?) throws -> FfiRecipeComponents {
return try FfiConverterTypeFfiRecipeComponents.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
uniffi_cooklang_import_fn_func_extract_recipe_from_url(
FfiConverterString.lower(url),
FfiConverterOptionUInt64.lower(timeoutSeconds), $0
)
})
}
/**
* Get the library version
*/
public func getVersion() -> String {
return try! FfiConverterString.lift(try! rustCall {
uniffi_cooklang_import_fn_func_get_version($0)
})
}
/**
* Import a recipe from a URL
*
* # Arguments
* * `url` - The URL of the recipe webpage
* * `config` - Optional configuration for the import
*
* # Returns
* An `FfiImportResult` containing either Cooklang text or a Recipe struct
*/
public func importFromUrl(url: String, config: FfiImportConfig?) throws -> FfiImportResult {
return try FfiConverterTypeFfiImportResult.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
uniffi_cooklang_import_fn_func_import_from_url(
FfiConverterString.lower(url),
FfiConverterOptionTypeFfiImportConfig.lower(config), $0
)
})
}
/**
* Check if a provider is available (has required environment variables)
*/
public func isProviderAvailable(provider: FfiLlmProvider) -> Bool {
return try! FfiConverterBool.lift(try! rustCall {
uniffi_cooklang_import_fn_func_is_provider_available(
FfiConverterTypeFfiLlmProvider.lower(provider), $0
)
})
}
/**
* Simple import from URL with default settings
*
* This is a convenience function that imports a recipe from a URL
* using default settings and returns the Cooklang-formatted result.
*
* # Arguments
* * `url` - The URL of the recipe webpage
*
* # Returns
* A string containing the recipe in Cooklang format
*/
public func simpleImport(url: String) throws -> String {
return try FfiConverterString.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
uniffi_cooklang_import_fn_func_simple_import(
FfiConverterString.lower(url), $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_cooklang_import_uniffi_contract_version()
if bindings_contract_version != scaffolding_contract_version {
return InitializationResult.contractVersionMismatch
}
if uniffi_cooklang_import_checksum_func_convert_image_to_cooklang() != 6900 {
return InitializationResult.apiChecksumMismatch
}
if uniffi_cooklang_import_checksum_func_convert_text_to_cooklang() != 2319 {
return InitializationResult.apiChecksumMismatch
}
if uniffi_cooklang_import_checksum_func_extract_recipe_from_url() != 45075 {
return InitializationResult.apiChecksumMismatch
}
if uniffi_cooklang_import_checksum_func_get_version() != 33295 {
return InitializationResult.apiChecksumMismatch
}
if uniffi_cooklang_import_checksum_func_import_from_url() != 49764 {
return InitializationResult.apiChecksumMismatch
}
if uniffi_cooklang_import_checksum_func_is_provider_available() != 42076 {
return InitializationResult.apiChecksumMismatch
}
if uniffi_cooklang_import_checksum_func_simple_import() != 32561 {
return InitializationResult.apiChecksumMismatch
}
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