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

    extern "Rust" {
        #[swift_bridge(swift_name = "createDefaultClient")]
        fn create_default_client(api_key: String, base_url: Option<String>) -> Result<DefaultClient, String>;
    }

    extern "Rust" {
        #[swift_bridge(swift_name = "defaultClientPing")]
        fn default_client_ping(client: &DefaultClient) -> String;
    }

    extern "Rust" {
        type DefaultClientChatStreamStreamHandle;

        #[swift_bridge(swift_name = "defaultClientChatStreamStart")]
        fn default_client_chat_stream_start(client: &DefaultClient, req: &ChatRequest) -> Result<DefaultClientChatStreamStreamHandle, String>;
        fn next(self: &mut DefaultClientChatStreamStreamHandle) -> Result<String, String>;
    }

}


pub struct DefaultClient(pub demo::DefaultClient);

pub fn create_default_client(api_key: String, base_url: Option<String>) -> Result<DefaultClient, String> {
Self { inner: ::demo::DefaultClient::new(api_key, base_url) }
}

pub fn default_client_ping(client: &DefaultClient) -> String {
    client.0.ping().to_string()
}

/// Opaque handle holding a reference to the process-wide tokio runtime
/// and a boxed `ChatChunk` stream.
///
/// Created by `default_client_chat_stream_start`, advanced via `next()`. Drop runs when the
/// Swift handle goes out of scope (swift-bridge generates the matching
/// `deinit`), so explicit cleanup from Swift is unnecessary.
///
/// Items are JSON-encoded at the bridge boundary because swift-bridge's
/// `Option<OpaqueRust>` support varies across versions, while `Result<String,
/// String>` is well-tested. An empty string `""` is the EOF sentinel -
/// no valid JSON value is the empty string.
#[allow(clippy::type_complexity)]
pub struct DefaultClientChatStreamStreamHandle {
    _rt: ::tokio::runtime::Handle,
    stream: ::std::sync::Mutex<
        Option<
            ::futures_util::stream::BoxStream<
                'static,
                Result<demo::ChatChunk, Box<dyn ::std::error::Error + Send + Sync + 'static>>,
            >,
        >,
    >,
}
/// Start a streaming `DefaultClient::chat_stream` request.
///
/// Returns a fresh `DefaultClientChatStreamStreamHandle` whose ownership transfers to the
/// Swift caller (swift-bridge boxes the handle internally).
pub fn default_client_chat_stream_start(client: &DefaultClient, req: &ChatRequest) -> Result<DefaultClientChatStreamStreamHandle, String> {
    use ::futures_util::StreamExt;
    let rt = crate::__alef_tokio_runtime();
    let raw = rt.block_on(async {
        demo::chat_stream(&client.0, req.0.clone())
            .await
            .map_err(|e| e.to_string())
    })?;
    let erased: ::futures_util::stream::BoxStream<
        'static,
        Result<demo::ChatChunk, Box<dyn ::std::error::Error + Send + Sync + 'static>>,
    > = Box::pin(
        raw.map(|r| r.map_err(|e| Box::new(e) as Box<dyn ::std::error::Error + Send + Sync + 'static>)),
    );
    Ok(DefaultClientChatStreamStreamHandle {
        _rt: rt.handle().clone(),
        stream: ::std::sync::Mutex::new(Some(erased)),
    })
}
#[allow(clippy::should_implement_trait)]
impl DefaultClientChatStreamStreamHandle {
    /// Advance the stream and return the next chunk JSON, or `""` on clean
    /// end-of-stream. Returns `Err(message)` on a stream-level error.
    pub fn next(&mut self) -> Result<String, String> {
        let mut guard = self
            .stream
            .lock()
            .map_err(|_| "DefaultClientChatStreamStreamHandle::next: stream mutex poisoned".to_string())?;
        let stream = match guard.as_mut() {
            Some(s) => s,
            None => return Ok(String::new()),
        };
        use ::futures_util::StreamExt;
        match crate::__alef_tokio_runtime().block_on(stream.next()) {
            Some(Ok(item)) => ::serde_json::to_string(&item).map_err(|e| e.to_string()),
            Some(Err(e)) => {
                *guard = None;
                Err(e.to_string())
            }
            None => {
                *guard = None;
                Ok(String::new())
            }
        }
    }
}
