---
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)]
#![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,
)]


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

    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 MarkupVisitorBox;
        fn alef_phantom_vec_markup_visitor() -> Vec<MarkupVisitorBox>;
        fn markup_visitor_call_visit_node(this: &MarkupVisitorBox, tag: String) -> FlowDecision;
    }

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

    extern "Rust" {

         #[swift_bridge(swift_name = "makeMarkupVisitorCallbackHandle")]
         fn make_markup_visitor_callback_handle(swift_box: SwiftMarkupVisitorBox) -> CallbackHandle;

    }

    extern "Rust" {

         #[swift_bridge(swift_name = "renderOptionsFromJsonWithVisitor")]
         fn render_options_from_json_with_visitor(json: String, visitor: Option<CallbackHandle>) -> Result<RenderOptions, String>;

    }

    extern "Rust" {
        #[swift_bridge(swift_name = "renderOptionsFromJson")]
        fn render_options_from_json(json: String) -> Result<RenderOptions, String>;
    }
}


pub struct CallbackHandle(pub demo::visitor::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 enum FlowDecision {
    Accept,
    Stop,
}

impl From<demo::visitor::FlowDecision> for FlowDecision {
    fn from(val: demo::visitor::FlowDecision) -> Self {
        match val {
            demo::visitor::FlowDecision::Accept => Self::Accept,
            demo::visitor::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 MarkupVisitorBox(pub Box<dyn demo::visitor::MarkupVisitor + Send + Sync>);
#[doc(hidden)]
pub fn alef_phantom_vec_markup_visitor() -> Vec<MarkupVisitorBox> { Vec::new() }
pub fn markup_visitor_call_visit_node(this: &MarkupVisitorBox, 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 `MarkupVisitor` 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 SwiftMarkupVisitorWrapper {
    inner: ffi::SwiftMarkupVisitorBox,
}
unsafe impl Send for SwiftMarkupVisitorWrapper {}
unsafe impl Sync for SwiftMarkupVisitorWrapper {}

impl SwiftMarkupVisitorWrapper {
    /// Construct a new wrapper from a Swift `SwiftMarkupVisitorBox` handle.
    pub fn new(inner: ffi::SwiftMarkupVisitorBox) -> Self {
        Self { inner }
    }
}
impl demo::visitor::MarkupVisitor for SwiftMarkupVisitorWrapper {
    fn visit_node(&self, tag: str) -> demo::visitor::FlowDecision {
        let json = self.inner.alef_visit_node(tag);
        ::serde_json::from_str::<demo::visitor::FlowDecision>(&json).expect("swift markup_visitor.visit_node returned invalid JSON")
    }

}


impl From<demo::visitor::CallbackHandle> for CallbackHandle {
    fn from(v: demo::visitor::CallbackHandle) -> Self { Self(v) }
}
impl From<CallbackHandle> for demo::visitor::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 `SwiftMarkupVisitorBox` handle.
/// Called by Swift e2e tests via `makeMarkupVisitorCallbackHandle(...)` to build a
/// `CallbackHandle` that can be passed to the options-with-visitor helper.
pub fn make_markup_visitor_callback_handle(swift_box: ffi::SwiftMarkupVisitorBox) -> CallbackHandle {
    let __wrapper = SwiftMarkupVisitorWrapper::new(swift_box);
    let __inner: demo::visitor::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
/// `visitor` 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_visitor(json: String, visitor: Option<CallbackHandle>) -> Result<RenderOptions, String> {
    let mut __core: demo::options::RenderOptions = ::serde_json::from_str(&json).map_err(|e| e.to_string())?;
    __core.visitor = visitor.map(|h| <demo::visitor::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())
}
