---
source: tests/backends_swift_snapshot_test.rs
expression: "&file.content"
---
// Generated by alef. Do not edit by hand.

#![allow(unused_variables, unreachable_code, unreachable_patterns, missing_docs)]
#![allow(
    clippy::collapsible_if,
    clippy::collapsible_match,
    clippy::needless_borrows_for_generic_args,
    clippy::field_reassign_with_default,
    clippy::too_many_arguments,
    clippy::clone_on_copy,
    clippy::unnecessary_cast,
    clippy::manual_flatten,
    clippy::match_single_binding,
    clippy::redundant_closure,
    clippy::useless_conversion,
    clippy::inherent_to_string,
    clippy::new_without_default,
)]


/// Process-wide tokio runtime shared across every swift-bridge async wrapper.
///
/// alef-emitted; see shims.rs for the rationale (orphaned reqwest connection
/// pools when each call creates and drops its own current-thread runtime).
fn __alef_tokio_runtime() -> &'static ::tokio::runtime::Runtime {
    use std::sync::OnceLock;
    static RT: OnceLock<::tokio::runtime::Runtime> = OnceLock::new();
    RT.get_or_init(|| {
        ::tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .expect("build process-wide alef tokio runtime")
    })
}

#[swift_bridge::bridge]
mod ffi {
    extern "Rust" {
        type CallbackHandle;
        fn callback_handle_noop(client: &CallbackHandle);
    }

    extern "Rust" {
        type RenderOptions;
        #[swift_bridge(init)]
        fn new(timeout_ms: u32) -> RenderOptions;
        #[swift_bridge(swift_name = "timeoutMs")]
        fn timeout_ms(&self) -> u32;
    }

    extern "Rust" {
        type MarkupCallbackBox;
        fn alef_phantom_vec_markup_callback() -> Vec<MarkupCallbackBox>;
        fn markup_callback_call_visit_node(this: &MarkupCallbackBox, tag: String) -> FlowDecision;
    }

    extern "Swift" {
        type SwiftMarkupCallbackBox;
        fn alef_visit_node(&self, tag: String) -> String;
    }

    extern "Rust" {

         #[swift_bridge(swift_name = "makeMarkupCallbackHandle")]
         fn make_markup_callback_callback_handle(swift_box: SwiftMarkupCallbackBox) -> CallbackHandle;

    }

    extern "Rust" {

         #[swift_bridge(swift_name = "renderOptionsFromJsonWithCallback")]
         fn render_options_from_json_with_callback(json: String, callback: Option<CallbackHandle>) -> Result<RenderOptions, String>;

    }

    extern "Rust" {
        #[swift_bridge(swift_name = "renderOptionsFromJson")]
        fn render_options_from_json(json: String) -> Result<RenderOptions, String>;
    }
    extern "Rust" {
        // Phantom Vec<T> functions: swift-bridge-build must emit the full Vec support
        // C ABI symbols (__swift_bridge__$Vec_T$new, drop, push, pop, get, get_mut, as_ptr, len)
        // which the auto-generated Swift Vec<T> conformances reference.
        //
        // swift-bridge 0.1.59 only emits these when Vec<T> appears as a return type
        // in an extern block. Without these phantom functions, Swift linker fails when
        // trying to construct or manipulate Vec<T> of opaque types.
        //
        // These declarations are paired with phantom_impl functions below the bridge module.
        fn __alef_phantom_vec_callback_handle() -> Vec<CallbackHandle>;
        fn __alef_phantom_vec_render_options() -> Vec<RenderOptions>;
    }

}

#[doc(hidden)]
pub fn __alef_phantom_vec_callback_handle() -> Vec<CallbackHandle> { Vec::new() }
#[doc(hidden)]
pub fn __alef_phantom_vec_render_options() -> Vec<RenderOptions> { Vec::new() }

pub struct CallbackHandle(pub demo::callbacks::CallbackHandle);

pub struct RenderOptions(pub demo::options::RenderOptions);
impl RenderOptions {
    pub fn new(timeout_ms: u32) -> RenderOptions {
        RenderOptions(demo::options::RenderOptions {
            timeout_ms,
        })
    }
    pub fn timeout_ms(&self) -> u32 {
        ::serde_json::to_value(&self.0.timeout_ms).ok().and_then(|j| ::serde_json::from_value(j).ok()).unwrap_or_default()
    }
}

pub fn callback_handle_noop(client: &CallbackHandle) {
    // No-op method for swift-bridge destructor synthesis
}

pub enum FlowDecision {
    Accept,
    Stop,
}

impl From<demo::callbacks::FlowDecision> for FlowDecision {
    fn from(val: demo::callbacks::FlowDecision) -> Self {
        match val {
            demo::callbacks::FlowDecision::Accept => Self::Accept,
            demo::callbacks::FlowDecision::Stop => Self::Stop,
        }
    }
}

impl FlowDecision {
    pub fn to_string(&self) -> String {
        match self {
            Self::Accept => "Accept".to_string(),
            Self::Stop => "Stop".to_string(),
        }
    }
}

pub struct MarkupCallbackBox(pub Box<dyn demo::callbacks::MarkupCallback + Send + Sync>);
#[doc(hidden)]
pub fn alef_phantom_vec_markup_callback() -> Vec<MarkupCallbackBox> { Vec::new() }
pub fn markup_callback_call_visit_node(this: &MarkupCallbackBox, tag: String) -> FlowDecision {
    FlowDecision::from(this.0.visit_node(tag))
}

/// Convert a stringified Swift error into the configured source-crate error type.
#[allow(dead_code)]
fn plugin_error_from_string(message: String) -> demo::Error {
    demo::Error::from(message)
}

/// JSON envelope returned by every fallible Swift trait method. Carries `Ok(T)`
/// as `{"ok": <serialised T>}` and `Err(String)` as `{"err": "<message>"}`.
/// Avoids swift-bridge 0.1.59's broken `Result<RustString, RustString>` codegen.
#[allow(dead_code)]
#[derive(::serde::Deserialize)]
#[serde(rename_all = "snake_case")]
enum InboundEnvelope<T> { Ok(T), Err(String) }

/// Deserialise a JSON envelope returned from a Swift FFI shim into a typed Result.
#[allow(dead_code)]
fn decode_inbound_envelope<T>(json: &str) -> std::result::Result<T, demo::Error>
where
    T: ::serde::de::DeserializeOwned,
{
    match ::serde_json::from_str::<InboundEnvelope<T>>(json) {
        Ok(InboundEnvelope::Ok(value)) => Ok(value),
        Ok(InboundEnvelope::Err(message)) => Err(plugin_error_from_string(message)),
        Err(e) => Err(plugin_error_from_string(format!("swift returned malformed envelope: {e}"))),
    }
}
/// Rust-side wrapper around a Swift class implementing the `MarkupCallback` protocol.
///
/// The Swift instance is held via a `swift-bridge` opaque handle that retains
/// the underlying ARC reference for the lifetime of this struct. Send + Sync are
/// asserted unsafely: Swift classes used as trait bridges must be thread-safe.
pub struct SwiftMarkupCallbackWrapper {
    inner: ffi::SwiftMarkupCallbackBox,
}
unsafe impl Send for SwiftMarkupCallbackWrapper {}
unsafe impl Sync for SwiftMarkupCallbackWrapper {}

impl SwiftMarkupCallbackWrapper {
    /// Construct a new wrapper from a Swift `SwiftMarkupCallbackBox` handle.
    pub fn new(inner: ffi::SwiftMarkupCallbackBox) -> Self {
        Self { inner }
    }
}
impl demo::callbacks::MarkupCallback for SwiftMarkupCallbackWrapper {
    fn visit_node(&self, tag: String) -> demo::callbacks::FlowDecision {
        let json = self.inner.alef_visit_node(tag);
        ::serde_json::from_str::<demo::callbacks::FlowDecision>(&json).expect("swift markup_callback.visit_node returned invalid JSON")
    }

}


impl From<demo::callbacks::CallbackHandle> for CallbackHandle {
    fn from(v: demo::callbacks::CallbackHandle) -> Self { Self(v) }
}
impl From<CallbackHandle> for demo::callbacks::CallbackHandle {
    fn from(v: CallbackHandle) -> Self { v.0 }
}
impl From<demo::options::RenderOptions> for RenderOptions {
    fn from(v: demo::options::RenderOptions) -> Self { Self(v) }
}

/// Construct a `CallbackHandle` from a Swift `SwiftMarkupCallbackBox` handle.
/// Called by Swift e2e tests via `makeMarkupCallbackHandle(...)` to build a
/// `CallbackHandle` that can be passed to the options-with-visitor helper.
pub fn make_markup_callback_callback_handle(swift_box: ffi::SwiftMarkupCallbackBox) -> CallbackHandle {
    let __wrapper = SwiftMarkupCallbackWrapper::new(swift_box);
    let __inner: demo::callbacks::CallbackHandle = ::std::sync::Arc::new(::std::sync::Mutex::new(__wrapper));
    CallbackHandle::from(__inner)
}

/// Deserialise a `RenderOptions` from JSON and attach a visitor handle to its
/// `callback` field. Used by Swift e2e tests to thread a `CallbackHandle` into the
/// conversion call without needing a mutable post-construction setter.
pub fn render_options_from_json_with_callback(json: String, callback: Option<CallbackHandle>) -> Result<RenderOptions, String> {
    let mut __core: demo::options::RenderOptions = ::serde_json::from_str(&json).map_err(|e| e.to_string())?;
    __core.callback = callback.map(|h| <demo::callbacks::CallbackHandle>::from(h));
    Ok(RenderOptions::from(__core))
}

pub fn render_options_from_json(json: String) -> Result<RenderOptions, String> {
    serde_json::from_str::<demo::options::RenderOptions>(&json)
        .map(RenderOptions)
        .map_err(|e| e.to_string())
}
