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 T: 'static,
291 R: 'static,
292 {
293 BoxMutatingFunctionOnce::new(move |t| self.apply(t))
294 }
295
296 /// Converts to a consuming closure `FnOnce(&mut T) -> R`
297 ///
298 /// Consumes `self` and returns a closure that, when invoked, calls
299 /// `apply(self, &mut T)`. This is the default, straightforward
300 /// implementation; types that can produce a more direct function pointer
301 /// or avoid additional captures may override it.
302 fn into_fn(self) -> impl FnOnce(&mut T) -> R
303 where
304 Self: Sized + 'static,
305 {
306 move |t| self.apply(t)
307 }
308
309 /// Non-consuming adapter to `BoxMutatingFunctionOnce`
310 ///
311 /// Creates a `BoxMutatingFunctionOnce<T, R>` that does not consume
312 /// `self`. The default implementation requires `Self: Clone` and clones
313 /// the receiver for the stored closure; the clone is consumed when the
314 /// boxed function is invoked. Types that can provide a zero-cost adapter
315 /// (for example clonable closures) should override this method to avoid
316 /// unnecessary allocations.
317 fn to_box(&self) -> BoxMutatingFunctionOnce<T, R>
318 where
319 Self: Sized + Clone + 'static,
320 T: 'static,
321 R: 'static,
322 {
323 self.clone().into_box()
324 }
325
326 /// Non-consuming adapter to a callable `FnOnce(&mut T) -> R`
327 ///
328 /// Returns a closure that does not consume `self`. The default requires
329 /// `Self: Clone` and clones `self` for the captured closure; the clone is
330 /// consumed when the returned closure is invoked. Implementors may
331 /// provide more efficient adapters for specific types.
332 fn to_fn(&self) -> impl FnOnce(&mut T) -> R
333 where
334 Self: Sized + Clone + 'static,
335 {
336 self.clone().into_fn()
337 }
338}
339
340// =======================================================================
341// 2. BoxMutatingFunctionOnce - Single Ownership Implementation
342// =======================================================================
343
344/// BoxMutatingFunctionOnce struct
345///
346/// A one-time mutating function implementation based on
347/// `Box<dyn FnOnce(&mut T) -> R>` for single ownership scenarios. This is
348/// the only MutatingFunctionOnce implementation type because FnOnce
349/// conflicts with shared ownership semantics.
350///
351/// # Features
352///
353/// - **Single Ownership**: Not cloneable, consumes self on use
354/// - **Zero Overhead**: No reference counting or locking
355/// - **Move Semantics**: Can capture and move variables
356/// - **Method Chaining**: Compose multiple operations via `and_then`
357/// - **Returns Results**: Unlike MutatorOnce, returns information
358///
359/// # Use Cases
360///
361/// Choose `BoxMutatingFunctionOnce` when:
362/// - Need to store FnOnce closures (with moved captured variables)
363/// - One-time resource transfer operations with results
364/// - Post-initialization callbacks that return status
365/// - Complex operations requiring ownership transfer and results
366///
367/// # Performance
368///
369/// `BoxMutatingFunctionOnce` performance characteristics:
370/// - No reference counting overhead
371/// - No lock acquisition or runtime borrow checking
372/// - Direct function call through vtable
373/// - Minimal memory footprint (single pointer)
374///
375/// # Why No Arc/Rc Variants?
376///
377/// FnOnce can only be called once, which conflicts with Arc/Rc shared
378/// ownership semantics:
379/// - Arc/Rc implies multiple owners might need to call
380/// - FnOnce is consumed after calling, cannot be called again
381/// - This semantic incompatibility makes Arc/Rc variants meaningless
382///
383/// # Examples
384///
385/// ## Basic Usage
386///
387/// ```rust
388/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
389///
390/// let data = vec![1, 2, 3];
391/// let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
392/// let old_len = x.len();
393/// x.extend(data); // Move data
394/// old_len
395/// });
396///
397/// let mut target = vec![0];
398/// let old_len = func.apply(&mut target);
399/// assert_eq!(old_len, 1);
400/// assert_eq!(target, vec![0, 1, 2, 3]);
401/// ```
402///
403/// ## Method Chaining
404///
405/// ```rust
406/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
407///
408/// let data1 = vec![1, 2];
409/// let data2 = vec![3, 4];
410///
411/// let chained = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
412/// x.extend(data1);
413/// x.len()
414/// })
415/// .and_then(move |x: &mut Vec<i32>| {
416/// x.extend(data2);
417/// x.len()
418/// });
419///
420/// let mut target = vec![0];
421/// let final_len = chained.apply(&mut target);
422/// assert_eq!(final_len, 5);
423/// assert_eq!(target, vec![0, 1, 2, 3, 4]);
424/// ```
425///
426/// # Author
427///
428/// Haixing Hu
429pub struct BoxMutatingFunctionOnce<T, R> {
430 function: Box<dyn FnOnce(&mut T) -> R>,
431 name: Option<String>,
432}
433
434impl<T, R> BoxMutatingFunctionOnce<T, R> {
435 // Generates: new(), new_with_name(), new_with_optional_name(), name(), set_name()
436 impl_function_common_methods!(
437 BoxMutatingFunctionOnce<T, R>,
438 (FnOnce(&mut T) -> R + 'static),
439 |f| Box::new(f)
440 );
441
442 // Generates: when(), and_then(), compose()
443 impl_box_function_methods!(
444 BoxMutatingFunctionOnce<T, R>,
445 BoxConditionalMutatingFunctionOnce,
446 FunctionOnce // chains a non-mutating function after this mutating function
447 );
448}
449
450impl<T, R> MutatingFunctionOnce<T, R> for BoxMutatingFunctionOnce<T, R> {
451 fn apply(self, input: &mut T) -> R {
452 (self.function)(input)
453 }
454
455 impl_box_once_conversions!(
456 BoxMutatingFunctionOnce<T, R>,
457 MutatingFunctionOnce,
458 FnOnce(&mut T) -> R
459 );
460}
461
462// Generates: identity() method for BoxMutatingFunctionOnce<T, T>
463impl_function_identity_method!(BoxMutatingFunctionOnce<T, T>, mutating);
464
465// Generates: Debug and Display implementations for BoxMutatingFunctionOnce<T, R>
466impl_function_debug_display!(BoxMutatingFunctionOnce<T, R>);
467
468// =======================================================================
469// 3. Implement MutatingFunctionOnce trait for closures
470// =======================================================================
471
472// Implement MutatingFunctionOnce for all FnOnce(&mut T) -> R using macro
473impl_closure_once_trait!(
474 MutatingFunctionOnce<T, R>,
475 apply,
476 BoxMutatingFunctionOnce,
477 FnOnce(input: &mut T) -> R
478);
479
480// =======================================================================
481// 4. Provide extension methods for closures
482// =======================================================================
483
484// Generates: FnMutatingFunctionOnceOps trait and blanket implementation
485impl_fn_ops_trait!(
486 (FnOnce(&mut T) -> R),
487 FnMutatingFunctionOnceOps,
488 BoxMutatingFunctionOnce,
489 FunctionOnce,
490 BoxConditionalMutatingFunctionOnce
491);
492
493// ============================================================================
494// BoxConditionalMutatingFunctionOnce - Box-based Conditional Mutating Function
495// ============================================================================
496
497/// BoxConditionalMutatingFunctionOnce struct
498///
499/// A conditional consuming transformer that only executes when a predicate is
500/// satisfied. Uses `BoxMutatingFunctionOnce` and `BoxPredicate` for single
501/// ownership semantics.
502///
503/// This type is typically created by calling `BoxMutatingFunctionOnce::when()` and
504/// is designed to work with the `or_else()` method to create if-then-else
505/// logic.
506///
507/// # Features
508///
509/// - **Single Ownership**: Not cloneable, consumes `self` on use
510/// - **One-time Use**: Can only be called once
511/// - **Conditional Execution**: Only transforms when predicate returns `true`
512/// - **Chainable**: Can add `or_else` branch to create if-then-else logic
513///
514/// # Examples
515///
516/// ## With or_else Branch
517///
518/// ```rust
519/// use qubit_function::{MutatingFunctionOnce, BoxMutatingFunctionOnce};
520///
521/// let double = BoxMutatingFunctionOnce::new(|x: &mut i32| x * 2);
522/// let negate = BoxMutatingFunctionOnce::new(|x: &mut i32| -x);
523/// let conditional = double.when(|x: &i32| *x > 0).or_else(negate);
524/// assert_eq!(conditional.apply(5), 10); // when branch executed
525///
526/// let double2 = BoxMutatingFunctionOnce::new(|x: &mut i32| x * 2);
527/// let negate2 = BoxMutatingFunctionOnce::new(|x: &mut i32| -x);
528/// let conditional2 = double2.when(|x: &i32| *x > 0).or_else(negate2);
529/// assert_eq!(conditional2.apply(-5), 5); // or_else branch executed
530/// ```
531///
532/// # Author
533///
534/// Haixing Hu
535pub struct BoxConditionalMutatingFunctionOnce<T, R> {
536 function: BoxMutatingFunctionOnce<T, R>,
537 predicate: BoxPredicate<T>,
538}
539
540// Use macro to generate conditional function implementations
541impl_box_conditional_function!(
542 BoxConditionalMutatingFunctionOnce<T, R>,
543 BoxMutatingFunctionOnce,
544 MutatingFunctionOnce
545);
546
547// Use macro to generate conditional function debug and display implementations
548impl_conditional_function_debug_display!(BoxConditionalMutatingFunctionOnce<T, R>);