qubit_function/functions/mutating_function_once.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! # MutatingFunctionOnce Types
10//!
11//! Provides Java-like one-time `MutatingFunction` interface implementations
12//! for performing operations that consume self, accept a mutable reference,
13//! and return a result.
14//!
15//! It is similar to the `FnOnce(&mut T) -> R` trait in the standard library.
16//!
17//! This module provides a unified `MutatingFunctionOnce` trait and a
18//! Box-based single ownership implementation:
19//!
20//! - **`BoxMutatingFunctionOnce<T, R>`**: Box-based single ownership
21//! implementation for one-time use scenarios
22//!
23//! # Design Philosophy
24//!
25//! The key difference between `MutatingFunctionOnce` and
26//! `MutatingFunction`:
27//!
28//! - **MutatingFunction**: `&self`, can be called multiple times, uses
29//! `Fn(&mut T) -> R`
30//! - **MutatingFunctionOnce**: `self`, can only be called once, uses
31//! `FnOnce(&mut T) -> R`
32//!
33//! ## MutatingFunctionOnce vs MutatingFunction
34//!
35//! | Feature | MutatingFunction | MutatingFunctionOnce |
36//! |---------|------------------|----------------------|
37//! | **Self Parameter** | `&self` | `self` |
38//! | **Call Count** | Multiple | Once |
39//! | **Closure Type** | `Fn(&mut T) -> R` | `FnOnce(&mut T) -> R` |
40//! | **Use Cases** | Repeatable operations | One-time resource
41//! transfers |
42//!
43//! # Why MutatingFunctionOnce?
44//!
45//! Core value of MutatingFunctionOnce:
46//!
47//! 1. **Store FnOnce closures**: Allows moving captured variables
48//! 2. **Delayed execution**: Store in data structures, execute later
49//! 3. **Resource transfer**: Suitable for scenarios requiring ownership
50//! transfer
51//! 4. **Return results**: Unlike MutatorOnce, returns information about the
52//! operation
53//!
54//! # Why Only Box Variant?
55//!
56//! - **Arc/Rc conflicts with FnOnce semantics**: FnOnce can only be called
57//! once, while shared ownership implies multiple references
58//! - **Box is perfect match**: Single ownership aligns perfectly with
59//! one-time call semantics
60//!
61//! # Use Cases
62//!
63//! ## BoxMutatingFunctionOnce
64//!
65//! - Post-initialization callbacks (moving data, returning status)
66//! - Resource transfer with result (moving Vec, returning old value)
67//! - One-time complex operations (requiring moved capture variables)
68//! - Validation with fixes (fix data once, return validation result)
69//!
70//! # Examples
71//!
72//! ## Basic Usage
73//!
74//! ```rust
75//! use qubit_function::{BoxMutatingFunctionOnce, MutatingFunctionOnce};
76//!
77//! let data = vec![1, 2, 3];
78//! let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
79//! let old_len = x.len();
80//! x.extend(data); // Move data
81//! old_len
82//! });
83//!
84//! let mut target = vec![0];
85//! let old_len = func.apply(&mut target);
86//! assert_eq!(old_len, 1);
87//! assert_eq!(target, vec![0, 1, 2, 3]);
88//! ```
89//!
90//! ## Method Chaining
91//!
92//! ```rust
93//! use qubit_function::{BoxMutatingFunctionOnce, MutatingFunctionOnce};
94//!
95//! let data1 = vec![1, 2];
96//! let data2 = vec![3, 4];
97//!
98//! let chained = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
99//! x.extend(data1);
100//! x.len()
101//! })
102//! .and_then(move |x: &mut Vec<i32>| {
103//! x.extend(data2);
104//! x.len()
105//! });
106//!
107//! let mut target = vec![0];
108//! let final_len = chained.apply(&mut target);
109//! assert_eq!(final_len, 5);
110//! assert_eq!(target, vec![0, 1, 2, 3, 4]);
111//! ```
112//!
113//! ## Validation Pattern
114//!
115//! ```rust
116//! use qubit_function::{BoxMutatingFunctionOnce, MutatingFunctionOnce};
117//!
118//! struct Data {
119//! value: i32,
120//! }
121//!
122//! let validator = BoxMutatingFunctionOnce::new(|data: &mut Data| {
123//! if data.value < 0 {
124//! data.value = 0;
125//! Err("Fixed negative value")
126//! } else {
127//! Ok("Valid")
128//! }
129//! });
130//!
131//! let mut data = Data { value: -5 };
132//! let result = validator.apply(&mut data);
133//! assert_eq!(data.value, 0);
134//! assert!(result.is_err());
135//! ```
136//!
137//! # Author
138//!
139//! Haixing Hu
140use crate::functions::{
141 function_once::FunctionOnce,
142 macros::{
143 impl_box_conditional_function,
144 impl_box_function_methods,
145 impl_conditional_function_debug_display,
146 impl_fn_ops_trait,
147 impl_function_common_methods,
148 impl_function_debug_display,
149 impl_function_identity_method,
150 },
151};
152use crate::macros::{
153 impl_box_once_conversions,
154 impl_closure_once_trait,
155};
156use crate::predicates::predicate::{
157 BoxPredicate,
158 Predicate,
159};
160
161// =======================================================================
162// 1. MutatingFunctionOnce Trait - One-time Function Interface
163// =======================================================================
164
165/// MutatingFunctionOnce trait - One-time mutating function interface
166///
167/// It is similar to the `FnOnce(&mut T) -> R` trait in the standard library.
168///
169/// Defines the core behavior of all one-time mutating function types.
170/// Performs operations that consume self, accept a mutable reference,
171/// potentially modify it, and return a result.
172///
173/// This trait is automatically implemented by:
174/// - All closures implementing `FnOnce(&mut T) -> R`
175/// - `BoxMutatingFunctionOnce<T, R>`
176///
177/// # Design Rationale
178///
179/// This trait provides a unified abstraction for one-time mutating function
180/// operations. The key difference from `MutatingFunction`:
181/// - `MutatingFunction` uses `&self`, can be called multiple times
182/// - `MutatingFunctionOnce` uses `self`, can only be called once
183///
184/// # Features
185///
186/// - **Unified Interface**: All one-time mutating functions share the same
187/// `apply` method signature
188/// - **Automatic Implementation**: Closures automatically implement this
189/// trait with zero overhead
190/// - **Type Conversions**: Provides `into_box` method for type conversion
191/// - **Generic Programming**: Write functions that work with any one-time
192/// mutating function type
193///
194/// # Examples
195///
196/// ## Generic Function
197///
198/// ```rust
199/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
200///
201/// fn apply<F: MutatingFunctionOnce<Vec<i32>, usize>>(
202/// func: F,
203/// initial: Vec<i32>
204/// ) -> (Vec<i32>, usize) {
205/// let mut val = initial;
206/// let result = func.apply(&mut val);
207/// (val, result)
208/// }
209///
210/// let data = vec![1, 2, 3];
211/// let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
212/// let old_len = x.len();
213/// x.extend(data);
214/// old_len
215/// });
216/// let (vec, old_len) = apply(func, vec![0]);
217/// assert_eq!(vec, vec![0, 1, 2, 3]);
218/// assert_eq!(old_len, 1);
219/// ```
220///
221/// ## Type Conversion
222///
223/// ```rust
224/// use qubit_function::MutatingFunctionOnce;
225///
226/// let data = vec![1, 2, 3];
227/// let closure = move |x: &mut Vec<i32>| {
228/// let old_len = x.len();
229/// x.extend(data);
230/// old_len
231/// };
232/// let box_func = closure.into_box();
233/// ```
234///
235/// # Author
236///
237/// Haixing Hu
238pub trait MutatingFunctionOnce<T, R> {
239 /// Performs the one-time mutating function operation
240 ///
241 /// Consumes self and executes an operation on the given mutable
242 /// reference, potentially modifying it, and returns a result. The
243 /// operation can only be called once.
244 ///
245 /// # Parameters
246 ///
247 /// * `t - A mutable reference to the input value
248 ///
249 /// # Returns
250 ///
251 /// The computed result value
252 ///
253 /// # Examples
254 ///
255 /// ```rust
256 /// use qubit_function::{MutatingFunctionOnce,
257 /// BoxMutatingFunctionOnce};
258 ///
259 /// let data = vec![1, 2, 3];
260 /// let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
261 /// let old_len = x.len();
262 /// x.extend(data);
263 /// old_len
264 /// });
265 ///
266 /// let mut target = vec![0];
267 /// let old_len = func.apply(&mut target);
268 /// assert_eq!(old_len, 1);
269 /// assert_eq!(target, vec![0, 1, 2, 3]);
270 /// ```
271 fn apply(self, t: &mut T) -> R;
272
273 /// Converts to `BoxMutatingFunctionOnce` (consuming)
274 ///
275 /// Consumes `self` and returns an owned `BoxMutatingFunctionOnce<T, R>`.
276 /// The default implementation simply wraps the consuming
277 /// `apply(self, &mut T)` call in a `Box<dyn FnOnce(&mut T) -> R>`.
278 /// Types that can provide a cheaper or identity conversion (for example
279 /// `BoxMutatingFunctionOnce` itself) should override this method.
280 ///
281 /// # Note
282 ///
283 /// - This method consumes the source value.
284 /// - Implementors may return `self` directly when `Self` is already a
285 /// `BoxMutatingFunctionOnce<T, R>` to avoid the extra wrapper
286 /// allocation.
287 fn into_box(self) -> BoxMutatingFunctionOnce<T, R>
288 where
289 Self: Sized + 'static,
290 {
291 BoxMutatingFunctionOnce::new(move |t| self.apply(t))
292 }
293
294 /// Converts to a consuming closure `FnOnce(&mut T) -> R`
295 ///
296 /// Consumes `self` and returns a closure that, when invoked, calls
297 /// `apply(self, &mut T)`. This is the default, straightforward
298 /// implementation; types that can produce a more direct function pointer
299 /// or avoid additional captures may override it.
300 fn into_fn(self) -> impl FnOnce(&mut T) -> R
301 where
302 Self: Sized + 'static,
303 {
304 move |t| self.apply(t)
305 }
306
307 /// Non-consuming adapter to `BoxMutatingFunctionOnce`
308 ///
309 /// Creates a `BoxMutatingFunctionOnce<T, R>` that does not consume
310 /// `self`. The default implementation requires `Self: Clone` and clones
311 /// the receiver for the stored closure; the clone is consumed when the
312 /// boxed function is invoked. Types that can provide a zero-cost adapter
313 /// (for example clonable closures) should override this method to avoid
314 /// unnecessary allocations.
315 fn to_box(&self) -> BoxMutatingFunctionOnce<T, R>
316 where
317 Self: Sized + Clone + 'static,
318 {
319 self.clone().into_box()
320 }
321
322 /// Non-consuming adapter to a callable `FnOnce(&mut T) -> R`
323 ///
324 /// Returns a closure that does not consume `self`. The default requires
325 /// `Self: Clone` and clones `self` for the captured closure; the clone is
326 /// consumed when the returned closure is invoked. Implementors may
327 /// provide more efficient adapters for specific types.
328 fn to_fn(&self) -> impl FnOnce(&mut T) -> R
329 where
330 Self: Sized + Clone + 'static,
331 {
332 self.clone().into_fn()
333 }
334}
335
336// =======================================================================
337// 2. BoxMutatingFunctionOnce - Single Ownership Implementation
338// =======================================================================
339
340/// BoxMutatingFunctionOnce struct
341///
342/// A one-time mutating function implementation based on
343/// `Box<dyn FnOnce(&mut T) -> R>` for single ownership scenarios. This is
344/// the only MutatingFunctionOnce implementation type because FnOnce
345/// conflicts with shared ownership semantics.
346///
347/// # Features
348///
349/// - **Single Ownership**: Not cloneable, consumes self on use
350/// - **Zero Overhead**: No reference counting or locking
351/// - **Move Semantics**: Can capture and move variables
352/// - **Method Chaining**: Compose multiple operations via `and_then`
353/// - **Returns Results**: Unlike MutatorOnce, returns information
354///
355/// # Use Cases
356///
357/// Choose `BoxMutatingFunctionOnce` when:
358/// - Need to store FnOnce closures (with moved captured variables)
359/// - One-time resource transfer operations with results
360/// - Post-initialization callbacks that return status
361/// - Complex operations requiring ownership transfer and results
362///
363/// # Performance
364///
365/// `BoxMutatingFunctionOnce` performance characteristics:
366/// - No reference counting overhead
367/// - No lock acquisition or runtime borrow checking
368/// - Direct function call through vtable
369/// - Minimal memory footprint (single pointer)
370///
371/// # Why No Arc/Rc Variants?
372///
373/// FnOnce can only be called once, which conflicts with Arc/Rc shared
374/// ownership semantics:
375/// - Arc/Rc implies multiple owners might need to call
376/// - FnOnce is consumed after calling, cannot be called again
377/// - This semantic incompatibility makes Arc/Rc variants meaningless
378///
379/// # Examples
380///
381/// ## Basic Usage
382///
383/// ```rust
384/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
385///
386/// let data = vec![1, 2, 3];
387/// let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
388/// let old_len = x.len();
389/// x.extend(data); // Move data
390/// old_len
391/// });
392///
393/// let mut target = vec![0];
394/// let old_len = func.apply(&mut target);
395/// assert_eq!(old_len, 1);
396/// assert_eq!(target, vec![0, 1, 2, 3]);
397/// ```
398///
399/// ## Method Chaining
400///
401/// ```rust
402/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
403///
404/// let data1 = vec![1, 2];
405/// let data2 = vec![3, 4];
406///
407/// let chained = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
408/// x.extend(data1);
409/// x.len()
410/// })
411/// .and_then(move |x: &mut Vec<i32>| {
412/// x.extend(data2);
413/// x.len()
414/// });
415///
416/// let mut target = vec![0];
417/// let final_len = chained.apply(&mut target);
418/// assert_eq!(final_len, 5);
419/// assert_eq!(target, vec![0, 1, 2, 3, 4]);
420/// ```
421///
422/// # Author
423///
424/// Haixing Hu
425pub struct BoxMutatingFunctionOnce<T, R> {
426 function: Box<dyn FnOnce(&mut T) -> R>,
427 name: Option<String>,
428}
429
430impl<T, R> BoxMutatingFunctionOnce<T, R> {
431 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
432 impl_function_common_methods!(
433 BoxMutatingFunctionOnce<T, R>,
434 (FnOnce(&mut T) -> R + 'static),
435 |f| Box::new(f)
436 );
437
438 // Generates: when(), and_then(), compose()
439 impl_box_function_methods!(
440 BoxMutatingFunctionOnce<T, R>,
441 BoxConditionalMutatingFunctionOnce,
442 FunctionOnce // chains a non-mutating function after this mutating function
443 );
444}
445
446impl<T, R> MutatingFunctionOnce<T, R> for BoxMutatingFunctionOnce<T, R> {
447 fn apply(self, input: &mut T) -> R {
448 (self.function)(input)
449 }
450
451 impl_box_once_conversions!(
452 BoxMutatingFunctionOnce<T, R>,
453 MutatingFunctionOnce,
454 FnOnce(&mut T) -> R
455 );
456}
457
458// Generates: identity() method for BoxMutatingFunctionOnce<T, T>
459impl_function_identity_method!(BoxMutatingFunctionOnce<T, T>, mutating);
460
461// Generates: Debug and Display implementations for BoxMutatingFunctionOnce<T, R>
462impl_function_debug_display!(BoxMutatingFunctionOnce<T, R>);
463
464// =======================================================================
465// 3. Implement MutatingFunctionOnce trait for closures
466// =======================================================================
467
468// Implement MutatingFunctionOnce for all FnOnce(&mut T) -> R using macro
469impl_closure_once_trait!(
470 MutatingFunctionOnce<T, R>,
471 apply,
472 BoxMutatingFunctionOnce,
473 FnOnce(input: &mut T) -> R
474);
475
476// =======================================================================
477// 4. Provide extension methods for closures
478// =======================================================================
479
480// Generates: FnMutatingFunctionOnceOps trait and blanket implementation
481impl_fn_ops_trait!(
482 (FnOnce(&mut T) -> R),
483 FnMutatingFunctionOnceOps,
484 BoxMutatingFunctionOnce,
485 FunctionOnce,
486 BoxConditionalMutatingFunctionOnce
487);
488
489// ============================================================================
490// BoxConditionalMutatingFunctionOnce - Box-based Conditional Mutating Function
491// ============================================================================
492
493/// BoxConditionalMutatingFunctionOnce struct
494///
495/// A conditional consuming transformer that only executes when a predicate is
496/// satisfied. Uses `BoxMutatingFunctionOnce` and `BoxPredicate` for single
497/// ownership semantics.
498///
499/// This type is typically created by calling `BoxMutatingFunctionOnce::when()` and
500/// is designed to work with the `or_else()` method to create if-then-else
501/// logic.
502///
503/// # Features
504///
505/// - **Single Ownership**: Not cloneable, consumes `self` on use
506/// - **One-time Use**: Can only be called once
507/// - **Conditional Execution**: Only transforms when predicate returns `true`
508/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
509///
510/// # Examples
511///
512/// ## With or_else Branch
513///
514/// ```rust
515/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
516///
517/// let double = BoxMutatingFunctionOnce::new(|x: &mut i32| x * 2);
518/// let negate = BoxMutatingFunctionOnce::new(|x: &mut i32| -x);
519/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
520/// assert_eq!(conditional.apply(5), 10); // when branch executed
521///
522/// let double2 = BoxMutatingFunctionOnce::new(|x: &mut i32| x * 2);
523/// let negate2 = BoxMutatingFunctionOnce::new(|x: &mut i32| -x);
524/// let conditional2 = double2.when(|x: &i32| *x > 0).or_else(negate2);
525/// assert_eq!(conditional2.apply(-5), 5); // or_else branch executed
526/// ```
527///
528/// # Author
529///
530/// Haixing Hu
531pub struct BoxConditionalMutatingFunctionOnce<T, R> {
532 function: BoxMutatingFunctionOnce<T, R>,
533 predicate: BoxPredicate<T>,
534}
535
536// Use macro to generate conditional function implementations
537impl_box_conditional_function!(
538 BoxConditionalMutatingFunctionOnce<T, R>,
539 BoxMutatingFunctionOnce,
540 MutatingFunctionOnce
541);
542
543// Use macro to generate conditional function debug and display implementations
544impl_conditional_function_debug_display!(BoxConditionalMutatingFunctionOnce<T, R>);