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