Skip to main content

qubit_function/functions/
function_once.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # FunctionOnce Types
10//!
11//! Provides Rust implementations of consuming function traits similar to
12//! Rust's `FnOnce(&T) -> R` trait, for computing output from input references.
13//!
14//! This module provides the `FunctionOnce<T, R>` trait and one-time use
15//! implementations:
16//!
17//! - [`BoxFunctionOnce`]: Single ownership, one-time use
18//!
19//! # Author
20//!
21//! Haixing Hu
22use crate::functions::macros::{
23    impl_box_conditional_function,
24    impl_box_function_methods,
25    impl_conditional_function_debug_display,
26    impl_fn_ops_trait,
27    impl_function_common_methods,
28    impl_function_constant_method,
29    impl_function_debug_display,
30    impl_function_identity_method,
31};
32use crate::macros::{
33    impl_box_once_conversions,
34    impl_closure_once_trait,
35};
36use crate::predicates::predicate::{
37    BoxPredicate,
38    Predicate,
39};
40
41// ============================================================================
42// Core Trait
43// ============================================================================
44
45/// FunctionOnce trait - consuming function that takes ownership
46///
47/// Defines the behavior of a consuming function: computing a value of
48/// type `R` from a reference to type `T` by taking ownership of self.
49/// This trait is analogous to `FnOnce(&T) -> R`.
50///
51/// # Type Parameters
52///
53/// * `T` - The type of the input value (borrowed)
54/// * `R` - The type of the output value
55///
56/// # Author
57///
58/// Haixing Hu
59pub trait FunctionOnce<T, R> {
60    /// Applies the function to the input reference, consuming self
61    ///
62    /// # Parameters
63    ///
64    /// * `t` - Reference to the input value
65    ///
66    /// # Returns
67    ///
68    /// The computed output value
69    fn apply(self, t: &T) -> R;
70
71    /// Converts to BoxFunctionOnce
72    ///
73    /// **⚠️ Consumes `self`**: The original function becomes unavailable
74    /// after calling this method.
75    ///
76    /// # Returns
77    ///
78    /// Returns `BoxFunctionOnce<T, R>`
79    ///
80    /// # Examples
81    ///
82    /// ```rust
83    /// use qubit_function::FunctionOnce;
84    ///
85    /// let double = |x: &i32| x * 2;
86    /// let boxed = double.into_box();
87    /// assert_eq!(boxed.apply(&21), 42);
88    /// ```
89    fn into_box(self) -> BoxFunctionOnce<T, R>
90    where
91        Self: Sized + 'static,
92    {
93        BoxFunctionOnce::new(move |input: &T| self.apply(input))
94    }
95
96    /// Converts function to a closure
97    ///
98    /// **⚠️ Consumes `self`**: The original function becomes unavailable
99    /// after calling this method.
100    ///
101    /// # Returns
102    ///
103    /// Returns a closure that implements `FnOnce(&T) -> R`
104    ///
105    /// # Examples
106    ///
107    /// ```rust
108    /// use qubit_function::FunctionOnce;
109    ///
110    /// let double = |x: &i32| x * 2;
111    /// let func = double.into_fn();
112    /// assert_eq!(func(&21), 42);
113    /// ```
114    fn into_fn(self) -> impl FnOnce(&T) -> R
115    where
116        Self: Sized + 'static,
117    {
118        move |input: &T| self.apply(input)
119    }
120
121    /// Converts to BoxFunctionOnce without consuming self
122    ///
123    /// **📌 Borrows `&self`**: The original function remains usable
124    /// after calling this method.
125    ///
126    /// # Default Implementation
127    ///
128    /// The default implementation creates a new `BoxFunctionOnce` that
129    /// captures a clone. Types implementing `Clone` can override this method
130    /// to provide more efficient conversions.
131    ///
132    /// # Returns
133    ///
134    /// Returns `BoxFunctionOnce<T, R>`
135    ///
136    /// # Examples
137    ///
138    /// ```rust
139    /// use qubit_function::FunctionOnce;
140    ///
141    /// let double = |x: &i32| x * 2;
142    /// let boxed = double.to_box();
143    /// assert_eq!(boxed.apply(&21), 42);
144    /// ```
145    fn to_box(&self) -> BoxFunctionOnce<T, R>
146    where
147        Self: Clone + 'static,
148    {
149        self.clone().into_box()
150    }
151
152    /// Converts function to a closure without consuming self
153    ///
154    /// **📌 Borrows `&self`**: The original function remains usable
155    /// after calling this method.
156    ///
157    /// # Default Implementation
158    ///
159    /// The default implementation creates a closure that captures a
160    /// clone of `self` and calls its `apply` method. Types can
161    /// override this method to provide more efficient conversions.
162    ///
163    /// # Returns
164    ///
165    /// Returns a closure that implements `FnOnce(&T) -> R`
166    ///
167    /// # Examples
168    ///
169    /// ```rust
170    /// use qubit_function::FunctionOnce;
171    ///
172    /// let double = |x: &i32| x * 2;
173    /// let func = double.to_fn();
174    /// assert_eq!(func(&21), 42);
175    /// ```
176    fn to_fn(&self) -> impl FnOnce(&T) -> R
177    where
178        Self: Clone + 'static,
179    {
180        self.clone().into_fn()
181    }
182}
183
184// ============================================================================
185// BoxFunctionOnce - Box<dyn FnOnce(&T) -> R>
186// ============================================================================
187
188/// BoxFunctionOnce - consuming transformer wrapper based on
189/// `Box<dyn FnOnce>`
190///
191/// A transformer wrapper that provides single ownership with one-time use
192/// semantics. Consumes both self and the input value.
193///
194/// # Features
195///
196/// - **Based on**: `Box<dyn FnOnce(&T) -> R>`
197/// - **Ownership**: Single ownership, cannot be cloned
198/// - **Reusability**: Can only be called once (consumes self and input)
199/// - **Thread Safety**: Not thread-safe (no `Send + Sync` requirement)
200///
201/// # Author
202///
203/// Haixing Hu
204pub struct BoxFunctionOnce<T, R> {
205    function: Box<dyn FnOnce(&T) -> R>,
206    name: Option<String>,
207}
208
209impl<T, R> BoxFunctionOnce<T, R> {
210    // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
211    impl_function_common_methods!(
212        BoxFunctionOnce<T, R>,
213        (FnOnce(&T) -> R + 'static),
214        |f| Box::new(f)
215    );
216
217    // Generates: when(), and_then(), compose()
218    impl_box_function_methods!(
219        BoxFunctionOnce<T, R>,
220        BoxConditionalFunctionOnce,
221        FunctionOnce
222    );
223}
224
225impl<T, R> FunctionOnce<T, R> for BoxFunctionOnce<T, R> {
226    fn apply(self, input: &T) -> R {
227        (self.function)(input)
228    }
229
230    impl_box_once_conversions!(
231        BoxFunctionOnce<T, R>,
232        FunctionOnce,
233        FnOnce(&T) -> R
234    );
235}
236
237// Generates: constant() method for BoxFunctionOnce<T, R>
238impl_function_constant_method!(BoxFunctionOnce<T, R>, 'static);
239
240// Generates: identity() method for BoxFunctionOnce<T, T>
241impl_function_identity_method!(BoxFunctionOnce<T, T>);
242
243// Generates: Debug and Display implementations for BoxFunctionOnce<T, R>
244impl_function_debug_display!(BoxFunctionOnce<T, R>);
245
246// ============================================================================
247// Blanket implementation for standard FnOnce trait
248// ============================================================================
249
250// Implement FunctionOnce for all FnOnce(&T) -> R using macro
251impl_closure_once_trait!(
252    FunctionOnce<T, R>,
253    apply,
254    BoxFunctionOnce,
255    FnOnce(input: &T) -> R
256);
257
258// ============================================================================
259// FnFunctionOnceOps - Extension trait for FnOnce transformers
260// ============================================================================
261
262// Generates: FnFunctionOnceOps trait and blanket implementation
263impl_fn_ops_trait!(
264    (FnOnce(&T) -> R),
265    FnFunctionOnceOps,
266    BoxFunctionOnce,
267    FunctionOnce,
268    BoxConditionalFunctionOnce
269);
270
271// ============================================================================
272// BoxConditionalFunctionOnce - Box-based Conditional Function
273// ============================================================================
274
275/// BoxConditionalFunctionOnce struct
276///
277/// A conditional consuming transformer that only executes when a predicate is
278/// satisfied. Uses `BoxFunctionOnce` and `BoxPredicate` for single
279/// ownership semantics.
280///
281/// This type is typically created by calling `BoxFunctionOnce::when()` and
282/// is designed to work with the `or_else()` method to create if-then-else
283/// logic.
284///
285/// # Features
286///
287/// - **Single Ownership**: Not cloneable, consumes `self` on use
288/// - **One-time Use**: Can only be called once
289/// - **Conditional Execution**: Only transforms when predicate returns `true`
290/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
291///
292/// # Examples
293///
294/// ## With or_else Branch
295///
296/// ```rust
297/// use qubit_function::{FunctionOnce, BoxFunctionOnce};
298///
299/// let double = BoxFunctionOnce::new(|x: i32| x * 2);
300/// let negate = BoxFunctionOnce::new(|x: i32| -x);
301/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
302/// assert_eq!(conditional.apply(5), 10); // when branch executed
303///
304/// let double2 = BoxFunctionOnce::new(|x: i32| x * 2);
305/// let negate2 = BoxFunctionOnce::new(|x: i32| -x);
306/// let conditional2 = double2.when(|x: &i32| *x > 0).or_else(negate2);
307/// assert_eq!(conditional2.apply(-5), 5); // or_else branch executed
308/// ```
309///
310/// # Author
311///
312/// Haixing Hu
313pub struct BoxConditionalFunctionOnce<T, R> {
314    function: BoxFunctionOnce<T, R>,
315    predicate: BoxPredicate<T>,
316}
317
318// Use macro to generate conditional function implementations
319impl_box_conditional_function!(
320    BoxConditionalFunctionOnce<T, R>,
321    BoxFunctionOnce,
322    FunctionOnce
323);
324
325// Use macro to generate conditional function debug and display implementations
326impl_conditional_function_debug_display!(BoxConditionalFunctionOnce<T, R>);