qubit-function 0.16.0

Functional programming traits and Box/Rc/Arc adapters for Rust, inspired by Java functional interfaces
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Defines the `BoxRunnableOnce` public type.

use crate::{
    macros::{
        impl_common_name_methods,
        impl_common_new_methods,
    },
    suppliers::{
        macros::impl_supplier_debug_display,
        supplier_once::SupplierOnce,
    },
    tasks::runnable_once::RunnableOnce,
};

use crate::tasks::callable_once::{
    BoxCallableOnce,
    CallableOnce,
};

// ============================================================================
// BoxRunnableOnce
// ============================================================================

/// Box-based one-time runnable.
///
/// `BoxRunnableOnce<E>` stores a
/// `Box<dyn FnOnce() -> Result<(), E> + Send>` and can be executed only once.
/// It is the boxed concrete implementation of [`RunnableOnce`] for task
/// objects that may be moved across threads.
///
/// # Type Parameters
///
/// * `E` - The error value returned when the action fails.
///
/// # Examples
///
/// ```rust
/// use qubit_function::{BoxRunnableOnce, RunnableOnce};
///
/// let task = BoxRunnableOnce::new(|| Ok::<(), String>(()));
/// assert_eq!(task.run_once(), Ok(()));
/// ```
#[must_use = "callback wrappers do nothing unless stored or invoked"]
pub struct BoxRunnableOnce<E> {
    /// The one-time closure executed by this runnable.
    pub(super) function: Box<dyn FnOnce() -> Result<(), E> + Send>,
    /// The optional name of this runnable.
    pub(super) metadata: crate::internal::CallbackMetadata,
}

impl<E> BoxRunnableOnce<E> {
    impl_common_new_methods!(
        semantic(RunnableOnce<E> + Send + 'static),
        |source| move || source.run_once(),
        |function| Box::new(function),
        "runnable"
    );

    /// Creates a boxed runnable from a one-time supplier.
    ///
    /// This is an explicit bridge from `SupplierOnce<Result<(), E>>` to
    /// `RunnableOnce<E>`.
    ///
    /// # Parameters
    ///
    /// * `supplier` - The supplier that produces the runnable result.
    ///
    /// # Returns
    ///
    /// A new `BoxRunnableOnce<E>`.
    #[inline]
    pub fn from_supplier<S>(supplier: S) -> Self
    where
        S: SupplierOnce<Result<(), E>> + Send + 'static,
    {
        Self::new(move || supplier.get())
    }

    impl_common_name_methods!("runnable");

    /// Chains another runnable after this runnable succeeds.
    ///
    /// The second runnable is not executed if this runnable returns `Err`.
    ///
    /// # Parameters
    ///
    /// * `next` - The runnable to execute after this runnable succeeds.
    ///
    /// # Returns
    ///
    /// A new runnable executing both actions in sequence.
    #[inline]
    pub fn and_then<N>(self, next: N) -> BoxRunnableOnce<E>
    where
        N: RunnableOnce<E> + Send + 'static,
        E: 'static,
    {
        let function = self.function;
        BoxRunnableOnce::new(move || {
            function()?;
            next.run_once()
        })
    }

    /// Runs this runnable before a callable.
    ///
    /// The callable is not executed if this runnable returns `Err`.
    /// Because this operation sequences two independent callbacks, the
    /// returned callable is unnamed.
    ///
    /// # Parameters
    ///
    /// * `callable` - The callable to execute after this runnable succeeds.
    ///
    /// # Returns
    ///
    /// A callable producing the second computation's result.
    #[inline]
    pub fn then_callable<R, C>(self, callable: C) -> BoxCallableOnce<R, E>
    where
        C: CallableOnce<R, E> + Send + 'static,
        R: 'static,
        E: 'static,
    {
        let function = self.function;
        BoxCallableOnce::new(move || {
            function()?;
            callable.call_once()
        })
    }
}

impl<E> RunnableOnce<E> for BoxRunnableOnce<E> {
    /// Executes the boxed runnable.
    #[inline(always)]
    fn run_once(self) -> Result<(), E> {
        (self.function)()
    }
}

impl<E> SupplierOnce<Result<(), E>> for BoxRunnableOnce<E> {
    /// Executes the boxed runnable as a one-time supplier of `Result<(), E>`.
    #[inline(always)]
    fn get(self) -> Result<(), E> {
        self.run_once()
    }
}

impl_supplier_debug_display!(BoxRunnableOnce<E>);