Skip to main content

qubit_function/suppliers/
stateful_supplier.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025 - 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Supplier Types
10//!
11//! Provides supplier implementations that generate and return values
12//! without taking any input parameters.
13//!
14//! # Overview
15//!
16//! A **Supplier** is a functional abstraction that generates and
17//! provides a value without accepting input. It can produce new
18//! values each time (like a factory) or return fixed values
19//! (like constants).
20//!
21//! This module implements **Approach 3** from the design document: a
22//! unified `Supplier` trait with multiple concrete implementations
23//! optimized for different ownership and concurrency scenarios.
24//!
25//! # Core Design Principles
26//!
27//! 1. **Returns Ownership**: `Supplier` returns `T` (not `&T`) to
28//!    avoid lifetime issues
29//! 2. **Uses `&mut self`**: Typical scenarios (counters, generators)
30//!    require state modification
31//! 3. **No ReadonlySupplier**: Main use cases require state
32//!    modification; value is extremely low
33//!
34//! # Three Implementations
35//!
36//! - **`BoxStatefulSupplier<T>`**: Single ownership using `Box<dyn FnMut()
37//!   -> T>`. Zero overhead, cannot be cloned. Best for one-time use
38//!   and builder patterns.
39//!
40//! - **`ArcStatefulSupplier<T>`**: Thread-safe shared ownership using
41//!   `Arc<Mutex<dyn FnMut() -> T + Send>>`. Can be cloned and sent
42//!   across threads. Higher overhead due to locking.
43//!
44//! - **`RcStatefulSupplier<T>`**: Single-threaded shared ownership using
45//!   `Rc<RefCell<dyn FnMut() -> T>>`. Can be cloned but not sent
46//!   across threads. Lower overhead than `ArcStatefulSupplier`.
47//!
48//! # Comparison with Other Functional Abstractions
49//!
50//! | Type      | Input | Output | self      | Modifies? | Use Case      |
51//! |-----------|-------|--------|-----------|-----------|---------------|
52//! | Supplier  | None  | `T`    | `&mut`    | Yes       | Factory       |
53//! | Consumer  | `&T`  | `()`   | `&mut`    | Yes       | Observer      |
54//! | Predicate | `&T`  | `bool` | `&self`   | No        | Filter        |
55//! | Function  | `&T`  | `R`    | `&self`   | No        | Transform     |
56//!
57//! # Examples
58//!
59//! ## Basic Counter
60//!
61//! ```rust
62//! use qubit_function::{BoxStatefulSupplier, Supplier};
63//!
64//! let mut counter = 0;
65//! let mut supplier = BoxStatefulSupplier::new(move || {
66//!     counter += 1;
67//!     counter
68//! });
69//!
70//! assert_eq!(supplier.get(), 1);
71//! assert_eq!(supplier.get(), 2);
72//! assert_eq!(supplier.get(), 3);
73//! ```
74//!
75//! ## Method Chaining
76//!
77//! ```rust
78//! use qubit_function::{BoxStatefulSupplier, Supplier};
79//!
80//! let mut pipeline = BoxStatefulSupplier::new(|| 10)
81//!     .map(|x| x * 2)
82//!     .map(|x| x + 5);
83//!
84//! assert_eq!(pipeline.get(), 25);
85//! ```
86//!
87//! ## Thread-safe Sharing
88//!
89//! ```rust
90//! use qubit_function::{ArcStatefulSupplier, Supplier};
91//! use std::sync::{Arc, Mutex};
92//! use std::thread;
93//!
94//! let counter = Arc::new(Mutex::new(0));
95//! let counter_clone = Arc::clone(&counter);
96//!
97//! let supplier = ArcStatefulSupplier::new(move || {
98//!     let mut c = counter_clone.lock().unwrap();
99//!     *c += 1;
100//!     *c
101//! });
102//!
103//! let mut s1 = supplier.clone();
104//! let mut s2 = supplier.clone();
105//!
106//! let h1 = thread::spawn(move || s1.get());
107//! let h2 = thread::spawn(move || s2.get());
108//!
109//! let v1 = h1.join().unwrap();
110//! let v2 = h2.join().unwrap();
111//!
112//! assert!(v1 != v2);
113//! assert_eq!(*counter.lock().unwrap(), 2);
114//! ```
115//!
116//! # Author
117//!
118//! Haixing Hu
119use std::cell::RefCell;
120use std::rc::Rc;
121use std::sync::Arc;
122
123use parking_lot::Mutex;
124
125use crate::macros::{
126    impl_arc_conversions,
127    impl_box_conversions,
128    impl_closure_trait,
129    impl_rc_conversions,
130};
131use crate::predicates::predicate::Predicate;
132use crate::suppliers::{
133    macros::{
134        impl_box_supplier_methods,
135        impl_shared_supplier_methods,
136        impl_supplier_clone,
137        impl_supplier_common_methods,
138        impl_supplier_debug_display,
139    },
140    supplier_once::BoxSupplierOnce,
141};
142use crate::transformers::transformer::Transformer;
143
144// ==========================================================================
145// Supplier Trait
146// ==========================================================================
147
148/// Supplier trait: generates and returns values without input.
149///
150/// The core abstraction for value generation. Similar to Java's
151/// `Supplier<T>` interface, it produces values without taking any
152/// input parameters.
153///
154/// # Key Characteristics
155///
156/// - **No input parameters**: Pure value generation
157/// - **Mutable access**: Uses `&mut self` to allow state changes
158/// - **Returns ownership**: Returns `T` (not `&T`) to avoid lifetime
159///   issues
160/// - **Can modify state**: Commonly used for counters, sequences,
161///   and generators
162///
163/// # Automatically Implemented for Closures
164///
165/// All `FnMut() -> T` closures automatically implement this trait,
166/// enabling seamless integration with both raw closures and wrapped
167/// supplier types.
168///
169/// # Examples
170///
171/// ## Using with Generic Functions
172///
173/// ```rust
174/// use qubit_function::{Supplier, BoxStatefulSupplier};
175///
176/// fn call_twice<S: StatefulSupplier<i32>>(supplier: &mut S) -> (i32, i32) {
177///     (supplier.get(), supplier.get())
178/// }
179///
180/// let mut s = BoxStatefulSupplier::new(|| 42);
181/// assert_eq!(call_twice(&mut s), (42, 42));
182///
183/// let mut closure = || 100;
184/// assert_eq!(call_twice(&mut closure), (100, 100));
185/// ```
186///
187/// ## Stateful Supplier
188///
189/// ```rust
190/// use qubit_function::Supplier;
191///
192/// let mut counter = 0;
193/// let mut stateful = || {
194///     counter += 1;
195///     counter
196/// };
197///
198/// assert_eq!(stateful.get(), 1);
199/// assert_eq!(stateful.get(), 2);
200/// ```
201///
202/// # Author
203///
204/// Haixing Hu
205pub trait StatefulSupplier<T> {
206    /// Generates and returns the next value.
207    ///
208    /// Executes the underlying function and returns the generated
209    /// value. Uses `&mut self` because suppliers typically involve
210    /// state changes (counters, sequences, etc.).
211    ///
212    /// # Returns
213    ///
214    /// The generated value of type `T`
215    ///
216    /// # Examples
217    ///
218    /// ```rust
219    /// use qubit_function::{Supplier, BoxStatefulSupplier};
220    ///
221    /// let mut supplier = BoxStatefulSupplier::new(|| 42);
222    /// assert_eq!(supplier.get(), 42);
223    /// ```
224    fn get(&mut self) -> T;
225
226    /// Converts to `BoxStatefulSupplier`.
227    ///
228    /// This method has a default implementation that wraps the
229    /// supplier in a `BoxStatefulSupplier`. Custom implementations can
230    /// override this for more efficient conversions.
231    ///
232    /// # Returns
233    ///
234    /// A new `BoxStatefulSupplier<T>` instance
235    ///
236    /// # Examples
237    ///
238    /// ```rust
239    /// use qubit_function::Supplier;
240    ///
241    /// let closure = || 42;
242    /// let mut boxed = closure.into_box();
243    /// assert_eq!(boxed.get(), 42);
244    /// ```
245    fn into_box(mut self) -> BoxStatefulSupplier<T>
246    where
247        Self: Sized + 'static,
248    {
249        BoxStatefulSupplier::new(move || self.get())
250    }
251
252    /// Converts to `RcStatefulSupplier`.
253    ///
254    /// This method has a default implementation that wraps the
255    /// supplier in an `RcStatefulSupplier`. Custom implementations can
256    /// override this for more efficient conversions.
257    ///
258    /// # Returns
259    ///
260    /// A new `RcStatefulSupplier<T>` instance
261    ///
262    /// # Examples
263    ///
264    /// ```rust
265    /// use qubit_function::Supplier;
266    ///
267    /// let closure = || 42;
268    /// let mut rc = closure.into_rc();
269    /// assert_eq!(rc.get(), 42);
270    /// ```
271    fn into_rc(mut self) -> RcStatefulSupplier<T>
272    where
273        Self: Sized + 'static,
274    {
275        RcStatefulSupplier::new(move || self.get())
276    }
277
278    /// Converts to `ArcStatefulSupplier`.
279    ///
280    /// This method has a default implementation that wraps the
281    /// supplier in an `ArcStatefulSupplier`. Custom implementations can
282    /// override this for more efficient conversions.
283    ///
284    /// # Returns
285    ///
286    /// A new `ArcStatefulSupplier<T>` instance
287    ///
288    /// # Examples
289    ///
290    /// ```rust
291    /// use qubit_function::Supplier;
292    ///
293    /// let closure = || 42;
294    /// let mut arc = closure.into_arc();
295    /// assert_eq!(arc.get(), 42);
296    /// ```
297    fn into_arc(mut self) -> ArcStatefulSupplier<T>
298    where
299        Self: Sized + Send + 'static,
300    {
301        ArcStatefulSupplier::new(move || self.get())
302    }
303
304    /// Converts to a closure `FnMut() -> T`.
305    ///
306    /// This method wraps the supplier in a closure that calls the
307    /// `get()` method when invoked. This allows using suppliers
308    /// in contexts that expect `FnMut()` closures.
309    ///
310    /// # Returns
311    ///
312    /// A closure `impl FnMut() -> T`
313    ///
314    /// # Examples
315    ///
316    /// ```rust
317    /// use qubit_function::{Supplier, BoxStatefulSupplier};
318    ///
319    /// let supplier = BoxStatefulSupplier::new(|| 42);
320    /// let mut closure = supplier.into_fn();
321    /// assert_eq!(closure(), 42);
322    /// assert_eq!(closure(), 42);
323    /// ```
324    ///
325    /// ## Using with functions that expect FnMut
326    ///
327    /// ```rust
328    /// use qubit_function::{Supplier, BoxStatefulSupplier};
329    ///
330    /// fn call_fn_twice<F: FnMut() -> i32>(mut f: F) -> (i32, i32) {
331    ///     (f(), f())
332    /// }
333    ///
334    /// let supplier = BoxStatefulSupplier::new(|| 100);
335    /// let closure = supplier.into_fn();
336    /// assert_eq!(call_fn_twice(closure), (100, 100));
337    /// ```
338    fn into_fn(mut self) -> impl FnMut() -> T
339    where
340        Self: Sized + 'static,
341    {
342        move || self.get()
343    }
344
345    /// Converts to `BoxSupplierOnce`.
346    ///
347    /// This method has a default implementation that wraps the
348    /// supplier in a `BoxSupplierOnce`. Custom implementations
349    /// can override this method for optimization purposes.
350    ///
351    /// # Returns
352    ///
353    /// A new `BoxSupplierOnce<T>` instance
354    ///
355    /// # Examples
356    ///
357    /// ```rust
358    /// use qubit_function::StatefulSupplier;
359    ///
360    /// let closure = || 42;
361    /// let once = closure.into_once();
362    /// assert_eq!(once.get(), 42);
363    /// ```
364    fn into_once(mut self) -> BoxSupplierOnce<T>
365    where
366        Self: Sized + 'static,
367    {
368        BoxSupplierOnce::new(move || self.get())
369    }
370
371    /// Creates a `BoxStatefulSupplier` from a cloned supplier.
372    ///
373    /// Uses `Clone` to obtain an owned copy and converts it into a
374    /// `BoxStatefulSupplier`. Implementations can override this for a more
375    /// efficient conversion.
376    fn to_box(&self) -> BoxStatefulSupplier<T>
377    where
378        Self: Clone + Sized + 'static,
379    {
380        self.clone().into_box()
381    }
382
383    /// Creates an `RcStatefulSupplier` from a cloned supplier.
384    ///
385    /// Uses `Clone` to obtain an owned copy and converts it into an
386    /// `RcStatefulSupplier`. Implementations can override it for better
387    /// performance.
388    fn to_rc(&self) -> RcStatefulSupplier<T>
389    where
390        Self: Clone + Sized + 'static,
391    {
392        self.clone().into_rc()
393    }
394
395    /// Creates an `ArcStatefulSupplier` from a cloned supplier.
396    ///
397    /// Requires the supplier and produced values to be `Send` so the
398    /// resulting supplier can be shared across threads.
399    fn to_arc(&self) -> ArcStatefulSupplier<T>
400    where
401        Self: Clone + Sized + Send + 'static,
402    {
403        self.clone().into_arc()
404    }
405
406    /// Creates a closure from a cloned supplier.
407    ///
408    /// The default implementation clones `self` and consumes the clone
409    /// to produce a closure. Concrete suppliers can override it to
410    /// avoid the additional clone.
411    fn to_fn(&self) -> impl FnMut() -> T
412    where
413        Self: Clone + Sized + 'static,
414    {
415        self.clone().into_fn()
416    }
417
418    /// Creates a `BoxSupplierOnce` from a cloned supplier
419    ///
420    /// Uses `Clone` to obtain an owned copy and converts it into a
421    /// `BoxSupplierOnce`. Requires `Self: Clone`. Custom implementations
422    /// can override this for better performance.
423    fn to_once(&self) -> BoxSupplierOnce<T>
424    where
425        Self: Clone + Sized + 'static,
426    {
427        self.clone().into_once()
428    }
429}
430
431// ==========================================================================
432// BoxStatefulSupplier - Single Ownership Implementation
433// ==========================================================================
434
435/// Box-based single ownership supplier.
436///
437/// Uses `Box<dyn FnMut() -> T>` for single ownership scenarios.
438/// This is the most lightweight supplier with zero reference
439/// counting overhead.
440///
441/// # Ownership Model
442///
443/// Methods consume `self` (move semantics). When you call a method
444/// like `map()`, the original supplier is consumed and you get a new
445/// one:
446///
447/// ```rust
448/// use qubit_function::{BoxStatefulSupplier, Supplier};
449///
450/// let supplier = BoxStatefulSupplier::new(|| 10);
451/// let mapped = supplier.map(|x| x * 2);
452/// // supplier is no longer usable here
453/// ```
454///
455/// # Examples
456///
457/// ## Counter
458///
459/// ```rust
460/// use qubit_function::{BoxStatefulSupplier, Supplier};
461///
462/// let mut counter = 0;
463/// let mut supplier = BoxStatefulSupplier::new(move || {
464///     counter += 1;
465///     counter
466/// });
467///
468/// assert_eq!(supplier.get(), 1);
469/// assert_eq!(supplier.get(), 2);
470/// ```
471///
472/// ## Method Chaining
473///
474/// ```rust
475/// use qubit_function::{BoxStatefulSupplier, Supplier};
476///
477/// let mut pipeline = BoxStatefulSupplier::new(|| 10)
478///     .map(|x| x * 2)
479///     .map(|x| x + 5);
480///
481/// assert_eq!(pipeline.get(), 25);
482/// ```
483///
484/// # Author
485///
486/// Haixing Hu
487pub struct BoxStatefulSupplier<T> {
488    function: Box<dyn FnMut() -> T>,
489    name: Option<String>,
490}
491
492impl<T> BoxStatefulSupplier<T> {
493    // Generates: new(), new_with_name(), name(), set_name(), constant()
494    impl_supplier_common_methods!(BoxStatefulSupplier<T>, (FnMut() -> T + 'static), |f| {
495        Box::new(f)
496    });
497
498    // Generates: map(), filter(), zip()
499    impl_box_supplier_methods!(BoxStatefulSupplier<T>, StatefulSupplier);
500
501    /// Creates a memoizing supplier.
502    ///
503    /// Returns a new supplier that caches the first value it
504    /// produces. All subsequent calls return the cached value.
505    ///
506    /// # Returns
507    ///
508    /// A new memoized `BoxStatefulSupplier<T>`
509    ///
510    /// # Examples
511    ///
512    /// ```rust
513    /// use qubit_function::{BoxStatefulSupplier, Supplier};
514    ///
515    /// let mut call_count = 0;
516    /// let mut memoized = BoxStatefulSupplier::new(move || {
517    ///     call_count += 1;
518    ///     42
519    /// }).memoize();
520    ///
521    /// assert_eq!(memoized.get(), 42); // Calls underlying function
522    /// assert_eq!(memoized.get(), 42); // Returns cached value
523    /// ```
524    pub fn memoize(mut self) -> BoxStatefulSupplier<T>
525    where
526        T: Clone + 'static,
527    {
528        let mut cache: Option<T> = None;
529        BoxStatefulSupplier::new(move || {
530            if let Some(ref cached) = cache {
531                cached.clone()
532            } else {
533                let value = StatefulSupplier::get(&mut self);
534                cache = Some(value.clone());
535                value
536            }
537        })
538    }
539}
540
541// Generates: Debug and Display implementations for BoxStatefulSupplier<T>
542impl_supplier_debug_display!(BoxStatefulSupplier<T>);
543
544impl<T> StatefulSupplier<T> for BoxStatefulSupplier<T> {
545    fn get(&mut self) -> T {
546        (self.function)()
547    }
548
549    // Generates: into_box(), into_rc(), into_fn(), into_once()
550    impl_box_conversions!(
551        BoxStatefulSupplier<T>,
552        RcStatefulSupplier,
553        FnMut() -> T,
554        BoxSupplierOnce
555    );
556}
557
558// ==========================================================================
559// RcStatefulSupplier - Single-threaded Shared Ownership Implementation
560// ==========================================================================
561
562/// Single-threaded shared ownership supplier.
563///
564/// Uses `Rc<RefCell<dyn FnMut() -> T>>` for single-threaded shared
565/// ownership. Can be cloned but not sent across threads.
566///
567/// # Ownership Model
568///
569/// Like `ArcStatefulSupplier`, methods borrow `&self` instead of consuming
570/// `self`:
571///
572/// ```rust
573/// use qubit_function::{RcStatefulSupplier, Supplier};
574///
575/// let source = RcStatefulSupplier::new(|| 10);
576/// let mapped = source.map(|x| x * 2);
577/// // source is still usable here!
578/// ```
579///
580/// # Examples
581///
582/// ## Shared Counter
583///
584/// ```rust
585/// use qubit_function::{RcStatefulSupplier, Supplier};
586/// use std::rc::Rc;
587/// use std::cell::RefCell;
588///
589/// let counter = Rc::new(RefCell::new(0));
590/// let counter_clone = Rc::clone(&counter);
591///
592/// let supplier = RcStatefulSupplier::new(move || {
593///     let mut c = counter_clone.borrow_mut();
594///     *c += 1;
595///     *c
596/// });
597///
598/// let mut s1 = supplier.clone();
599/// let mut s2 = supplier.clone();
600/// assert_eq!(s1.get(), 1);
601/// assert_eq!(s2.get(), 2);
602/// ```
603///
604/// ## Reusable Transformations
605///
606/// ```rust
607/// use qubit_function::{RcStatefulSupplier, Supplier};
608///
609/// let base = RcStatefulSupplier::new(|| 10);
610/// let doubled = base.map(|x| x * 2);
611/// let tripled = base.map(|x| x * 3);
612///
613/// let mut b = base;
614/// let mut d = doubled;
615/// let mut t = tripled;
616/// assert_eq!(b.get(), 10);
617/// assert_eq!(d.get(), 20);
618/// assert_eq!(t.get(), 30);
619/// ```
620///
621/// # Author
622///
623/// Haixing Hu
624pub struct RcStatefulSupplier<T> {
625    function: Rc<RefCell<dyn FnMut() -> T>>,
626    name: Option<String>,
627}
628
629impl<T> RcStatefulSupplier<T> {
630    // Generates: new(), new_with_name(), name(), set_name(), constant()
631    impl_supplier_common_methods!(
632        RcStatefulSupplier<T>,
633        (FnMut() -> T + 'static),
634        |f| Rc::new(RefCell::new(f))
635    );
636
637    // Generates: map(), filter(), zip()
638    impl_shared_supplier_methods!(
639        RcStatefulSupplier<T>,
640        StatefulSupplier,
641        ('static)
642    );
643
644    /// Creates a memoizing supplier.
645    ///
646    /// # Returns
647    ///
648    /// A new memoized `RcStatefulSupplier<T>`
649    ///
650    /// # Examples
651    ///
652    /// ```rust
653    /// use qubit_function::{RcStatefulSupplier, Supplier};
654    /// use std::rc::Rc;
655    /// use std::cell::RefCell;
656    ///
657    /// let call_count = Rc::new(RefCell::new(0));
658    /// let call_count_clone = Rc::clone(&call_count);
659    /// let source = RcStatefulSupplier::new(move || {
660    ///     let mut c = call_count_clone.borrow_mut();
661    ///     *c += 1;
662    ///     42
663    /// });
664    /// let memoized = source.memoize();
665    ///
666    /// let mut s = memoized;
667    /// assert_eq!(s.get(), 42); // Calls underlying function
668    /// assert_eq!(s.get(), 42); // Returns cached value
669    /// assert_eq!(*call_count.borrow(), 1);
670    /// ```
671    pub fn memoize(&self) -> RcStatefulSupplier<T>
672    where
673        T: Clone + 'static,
674    {
675        let self_fn = Rc::clone(&self.function);
676        let cache: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
677        RcStatefulSupplier {
678            function: Rc::new(RefCell::new(move || {
679                let mut cache_ref = cache.borrow_mut();
680                if let Some(ref cached) = *cache_ref {
681                    cached.clone()
682                } else {
683                    let value = self_fn.borrow_mut()();
684                    *cache_ref = Some(value.clone());
685                    value
686                }
687            })),
688            name: None,
689        }
690    }
691}
692
693// Generates: Debug and Display implementations for RcStatefulSupplier<T>
694impl_supplier_debug_display!(RcStatefulSupplier<T>);
695
696// Generates: Clone implementation for RcStatefulSupplier<T>
697impl_supplier_clone!(RcStatefulSupplier<T>);
698
699impl<T> StatefulSupplier<T> for RcStatefulSupplier<T> {
700    fn get(&mut self) -> T {
701        (self.function.borrow_mut())()
702    }
703
704    // Generate all conversion methods using the unified macro
705    impl_rc_conversions!(
706        RcStatefulSupplier<T>,
707        BoxStatefulSupplier,
708        BoxSupplierOnce,
709        FnMut() -> T
710    );
711}
712
713// ==========================================================================
714// ArcStatefulSupplier - Thread-safe Shared Ownership Implementation
715// ==========================================================================
716
717/// Thread-safe shared ownership supplier.
718///
719/// Uses `Arc<Mutex<dyn FnMut() -> T + Send>>` for thread-safe
720/// shared ownership. Can be cloned and sent across threads.
721///
722/// # Ownership Model
723///
724/// Methods borrow `&self` instead of consuming `self`. The original
725/// supplier remains usable after method calls:
726///
727/// ```rust
728/// use qubit_function::{ArcStatefulSupplier, Supplier};
729///
730/// let source = ArcStatefulSupplier::new(|| 10);
731/// let mapped = source.map(|x| x * 2);
732/// // source is still usable here!
733/// ```
734///
735/// # Examples
736///
737/// ## Thread-safe Counter
738///
739/// ```rust
740/// use qubit_function::{ArcStatefulSupplier, Supplier};
741/// use std::sync::{Arc, Mutex};
742/// use std::thread;
743///
744/// let counter = Arc::new(Mutex::new(0));
745/// let counter_clone = Arc::clone(&counter);
746///
747/// let supplier = ArcStatefulSupplier::new(move || {
748///     let mut c = counter_clone.lock().unwrap();
749///     *c += 1;
750///     *c
751/// });
752///
753/// let mut s1 = supplier.clone();
754/// let mut s2 = supplier.clone();
755///
756/// let h1 = thread::spawn(move || s1.get());
757/// let h2 = thread::spawn(move || s2.get());
758///
759/// let v1 = h1.join().unwrap();
760/// let v2 = h2.join().unwrap();
761/// assert!(v1 != v2);
762/// ```
763///
764/// ## Reusable Transformations
765///
766/// ```rust
767/// use qubit_function::{ArcStatefulSupplier, Supplier};
768///
769/// let base = ArcStatefulSupplier::new(|| 10);
770/// let doubled = base.map(|x| x * 2);
771/// let tripled = base.map(|x| x * 3);
772///
773/// // All remain usable
774/// let mut b = base;
775/// let mut d = doubled;
776/// let mut t = tripled;
777/// assert_eq!(b.get(), 10);
778/// assert_eq!(d.get(), 20);
779/// assert_eq!(t.get(), 30);
780/// ```
781///
782/// # Author
783///
784/// Haixing Hu
785pub struct ArcStatefulSupplier<T> {
786    function: Arc<Mutex<dyn FnMut() -> T + Send>>,
787    name: Option<String>,
788}
789
790impl<T> ArcStatefulSupplier<T> {
791    // Generates: new(), new_with_name(), name(), set_name()
792    // Note: constant() is NOT generated here, implemented separately below
793    crate::macros::impl_common_new_methods!(
794        (FnMut() -> T + Send + 'static),
795        |f| Arc::new(Mutex::new(f)),
796        "supplier"
797    );
798
799    crate::macros::impl_common_name_methods!("supplier");
800
801    // Generates: map(), filter(), zip()
802    impl_shared_supplier_methods!(ArcStatefulSupplier<T>, StatefulSupplier, (arc));
803}
804
805// Separate impl block for constant() and memoize() with stricter T: Send bound
806impl<T> ArcStatefulSupplier<T> {
807    /// Creates a supplier that returns a constant value.
808    ///
809    /// Creates a supplier that always returns the same value. Useful for
810    /// default values or placeholder implementations.
811    ///
812    /// **Note:** This method requires `T: Send` because the constant value
813    /// is captured by a `FnMut` closure which will be stored in an `Arc<Mutex<...>>`.
814    ///
815    /// # Parameters
816    ///
817    /// * `value` - The constant value to return
818    ///
819    /// # Returns
820    ///
821    /// Returns a new supplier instance that returns the constant value.
822    ///
823    /// # Examples
824    ///
825    /// ```rust
826    /// use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
827    ///
828    /// let mut supplier = ArcStatefulSupplier::constant(42);
829    /// assert_eq!(supplier.get(), 42);
830    /// assert_eq!(supplier.get(), 42); // Can be called multiple times
831    /// ```
832    pub fn constant(value: T) -> Self
833    where
834        T: Clone + Send + 'static,
835    {
836        Self::new(move || value.clone())
837    }
838
839    /// Creates a memoizing supplier.
840    ///
841    /// **Note:** This method requires `T: Send` because the cached value
842    /// needs to be shared across threads via `Arc<Mutex<...>>`.
843    ///
844    /// # Returns
845    ///
846    /// A new memoized `ArcStatefulSupplier<T>`
847    ///
848    /// # Examples
849    ///
850    /// ```rust
851    /// use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
852    /// use std::sync::{Arc, Mutex};
853    ///
854    /// let call_count = Arc::new(Mutex::new(0));
855    /// let call_count_clone = Arc::clone(&call_count);
856    /// let source = ArcStatefulSupplier::new(move || {
857    ///     let mut c = call_count_clone.lock();
858    ///     *c += 1;
859    ///     42
860    /// });
861    /// let memoized = source.memoize();
862    ///
863    /// let mut s = memoized;
864    /// assert_eq!(s.get(), 42); // Calls underlying function
865    /// assert_eq!(s.get(), 42); // Returns cached value
866    /// assert_eq!(*call_count.lock(), 1);
867    /// ```
868    pub fn memoize(&self) -> ArcStatefulSupplier<T>
869    where
870        T: Clone + Send + 'static,
871    {
872        let self_fn = Arc::clone(&self.function);
873        let cache: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
874        ArcStatefulSupplier {
875            function: Arc::new(Mutex::new(move || {
876                let mut cache_guard = cache.lock();
877                if let Some(ref cached) = *cache_guard {
878                    cached.clone()
879                } else {
880                    let value = self_fn.lock()();
881                    *cache_guard = Some(value.clone());
882                    value
883                }
884            })),
885            name: None,
886        }
887    }
888}
889
890// Generates: Debug and Display implementations for ArcStatefulSupplier<T>
891impl_supplier_debug_display!(ArcStatefulSupplier<T>);
892
893// Generates: Clone implementation for ArcStatefulSupplier<T>
894impl_supplier_clone!(ArcStatefulSupplier<T>);
895
896impl<T> StatefulSupplier<T> for ArcStatefulSupplier<T> {
897    fn get(&mut self) -> T {
898        (self.function.lock())()
899    }
900
901    // Use macro to implement conversion methods
902    impl_arc_conversions!(
903        ArcStatefulSupplier<T>,
904        BoxStatefulSupplier,
905        RcStatefulSupplier,
906        BoxSupplierOnce,
907        FnMut() -> T
908    );
909}
910
911// ==========================================================================
912// Implement StatefulSupplier for Closures
913// ==========================================================================
914
915// Implement StatefulSupplier<T> for any type that implements FnMut() -> T
916impl_closure_trait!(
917    StatefulSupplier<T>,
918    get,
919    BoxSupplierOnce,
920    FnMut() -> T
921);
922
923// ==========================================================================
924// Extension Trait for Closure Operations
925// ==========================================================================
926
927/// Extension trait providing supplier operations for closures
928///
929/// Provides composition methods (`map`, `filter`, `zip`, `memoize`) for
930/// closures implementing `FnMut() -> T` without requiring explicit
931/// wrapping in `BoxStatefulSupplier`.
932///
933/// This trait is automatically implemented for all closures and function
934/// pointers that implement `FnMut() -> T`.
935///
936/// # Design Rationale
937///
938/// While closures automatically implement `Supplier<T>` through blanket
939/// implementation, they don't have access to instance methods like
940/// `map`, `filter`, and `zip`. This extension trait provides those
941/// methods, returning `BoxStatefulSupplier` for maximum flexibility.
942///
943/// # Examples
944///
945/// ## Map transformation
946///
947/// ```rust
948/// use qubit_function::{Supplier, FnStatefulSupplierOps};
949///
950/// let mut counter = 0;
951/// let mut mapped = (move || {
952///     counter += 1;
953///     counter
954/// }).map(|x| x * 2);
955///
956/// assert_eq!(mapped.get(), 2);
957/// assert_eq!(mapped.get(), 4);
958/// ```
959///
960/// ## Filter values
961///
962/// ```rust
963/// use qubit_function::{Supplier, FnStatefulSupplierOps};
964///
965/// let mut counter = 0;
966/// let mut filtered = (move || {
967///     counter += 1;
968///     counter
969/// }).filter(|x| x % 2 == 0);
970///
971/// assert_eq!(filtered.get(), None);     // 1 is odd
972/// assert_eq!(filtered.get(), Some(2));  // 2 is even
973/// ```
974///
975/// ## Combine with zip
976///
977/// ```rust
978/// use qubit_function::{Supplier, FnStatefulSupplierOps, BoxStatefulSupplier};
979///
980/// let first = || 42;
981/// let second = BoxStatefulSupplier::new(|| "hello");
982/// let mut zipped = first.zip(second);
983///
984/// assert_eq!(zipped.get(), (42, "hello"));
985/// ```
986///
987/// # Author
988///
989/// Haixing Hu
990pub trait FnStatefulSupplierOps<T>: FnMut() -> T + Sized {
991    /// Maps the output using a transformation function.
992    ///
993    /// Consumes the closure and returns a new supplier that applies
994    /// the mapper to each output.
995    ///
996    /// # Parameters
997    ///
998    /// * `mapper` - The mapper to apply to the output
999    ///
1000    /// # Returns
1001    ///
1002    /// A new mapped `BoxStatefulSupplier<U>`
1003    ///
1004    /// # Examples
1005    ///
1006    /// ```rust
1007    /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1008    ///
1009    /// let mut mapped = (|| 10)
1010    ///     .map(|x| x * 2)
1011    ///     .map(|x| x + 5);
1012    /// assert_eq!(mapped.get(), 25);
1013    /// ```
1014    fn map<U, M>(self, mapper: M) -> BoxStatefulSupplier<U>
1015    where
1016        Self: 'static,
1017        M: Transformer<T, U> + 'static,
1018        U: 'static,
1019        T: 'static,
1020    {
1021        BoxStatefulSupplier::new(self).map(mapper)
1022    }
1023
1024    /// Filters output based on a predicate.
1025    ///
1026    /// Returns a new supplier that returns `Some(value)` if the
1027    /// predicate is satisfied, `None` otherwise.
1028    ///
1029    /// # Parameters
1030    ///
1031    /// * `predicate` - The predicate to test the supplied value
1032    ///
1033    /// # Returns
1034    ///
1035    /// A new filtered `BoxStatefulSupplier<Option<T>>`
1036    ///
1037    /// # Examples
1038    ///
1039    /// ```rust
1040    /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1041    ///
1042    /// let mut counter = 0;
1043    /// let mut filtered = (move || {
1044    ///     counter += 1;
1045    ///     counter
1046    /// }).filter(|x| x % 2 == 0);
1047    ///
1048    /// assert_eq!(filtered.get(), None);     // 1 is odd
1049    /// assert_eq!(filtered.get(), Some(2));  // 2 is even
1050    /// ```
1051    fn filter<P>(self, predicate: P) -> BoxStatefulSupplier<Option<T>>
1052    where
1053        Self: 'static,
1054        P: Predicate<T> + 'static,
1055        T: 'static,
1056    {
1057        BoxStatefulSupplier::new(self).filter(predicate)
1058    }
1059
1060    /// Combines this supplier with another, producing a tuple.
1061    ///
1062    /// Consumes both suppliers and returns a new supplier that
1063    /// produces `(T, U)` tuples.
1064    ///
1065    /// # Parameters
1066    ///
1067    /// * `other` - The other supplier to combine with. Can be any type
1068    ///   implementing `Supplier<U>`
1069    ///
1070    /// # Returns
1071    ///
1072    /// A new `BoxStatefulSupplier<(T, U)>`
1073    ///
1074    /// # Examples
1075    ///
1076    /// ```rust
1077    /// use qubit_function::{Supplier, FnStatefulSupplierOps, BoxStatefulSupplier};
1078    ///
1079    /// let first = || 42;
1080    /// let second = BoxStatefulSupplier::new(|| "hello");
1081    /// let mut zipped = first.zip(second);
1082    ///
1083    /// assert_eq!(zipped.get(), (42, "hello"));
1084    /// ```
1085    fn zip<S, U>(self, other: S) -> BoxStatefulSupplier<(T, U)>
1086    where
1087        Self: 'static,
1088        S: StatefulSupplier<U> + 'static,
1089        U: 'static,
1090        T: 'static,
1091    {
1092        BoxStatefulSupplier::new(self).zip(other)
1093    }
1094
1095    /// Creates a memoizing supplier.
1096    ///
1097    /// Returns a new supplier that caches the first value it
1098    /// produces. All subsequent calls return the cached value.
1099    ///
1100    /// # Returns
1101    ///
1102    /// A new memoized `BoxStatefulSupplier<T>`
1103    ///
1104    /// # Examples
1105    ///
1106    /// ```rust
1107    /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1108    ///
1109    /// let mut call_count = 0;
1110    /// let mut memoized = (move || {
1111    ///     call_count += 1;
1112    ///     42
1113    /// }).memoize();
1114    ///
1115    /// assert_eq!(memoized.get(), 42); // Calls underlying function
1116    /// assert_eq!(memoized.get(), 42); // Returns cached value
1117    /// ```
1118    fn memoize(self) -> BoxStatefulSupplier<T>
1119    where
1120        Self: 'static,
1121        T: Clone + 'static,
1122    {
1123        BoxStatefulSupplier::new(self).memoize()
1124    }
1125}
1126
1127// Implement the extension trait for all closures
1128impl<T, F> FnStatefulSupplierOps<T> for F where F: FnMut() -> T + Sized {}