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 T: 'static,
249 {
250 BoxStatefulSupplier::new(move || self.get())
251 }
252
253 /// Converts to `RcStatefulSupplier`.
254 ///
255 /// This method has a default implementation that wraps the
256 /// supplier in an `RcStatefulSupplier`. Custom implementations can
257 /// override this for more efficient conversions.
258 ///
259 /// # Returns
260 ///
261 /// A new `RcStatefulSupplier<T>` instance
262 ///
263 /// # Examples
264 ///
265 /// ```rust
266 /// use qubit_function::Supplier;
267 ///
268 /// let closure = || 42;
269 /// let mut rc = closure.into_rc();
270 /// assert_eq!(rc.get(), 42);
271 /// ```
272 fn into_rc(mut self) -> RcStatefulSupplier<T>
273 where
274 Self: Sized + 'static,
275 T: 'static,
276 {
277 RcStatefulSupplier::new(move || self.get())
278 }
279
280 /// Converts to `ArcStatefulSupplier`.
281 ///
282 /// This method has a default implementation that wraps the
283 /// supplier in an `ArcStatefulSupplier`. Custom implementations can
284 /// override this for more efficient conversions.
285 ///
286 /// # Returns
287 ///
288 /// A new `ArcStatefulSupplier<T>` instance
289 ///
290 /// # Examples
291 ///
292 /// ```rust
293 /// use qubit_function::Supplier;
294 ///
295 /// let closure = || 42;
296 /// let mut arc = closure.into_arc();
297 /// assert_eq!(arc.get(), 42);
298 /// ```
299 fn into_arc(mut self) -> ArcStatefulSupplier<T>
300 where
301 Self: Sized + Send + 'static,
302 T: 'static,
303 {
304 ArcStatefulSupplier::new(move || self.get())
305 }
306
307 /// Converts to a closure `FnMut() -> T`.
308 ///
309 /// This method wraps the supplier in a closure that calls the
310 /// `get()` method when invoked. This allows using suppliers
311 /// in contexts that expect `FnMut()` closures.
312 ///
313 /// # Returns
314 ///
315 /// A closure `impl FnMut() -> T`
316 ///
317 /// # Examples
318 ///
319 /// ```rust
320 /// use qubit_function::{Supplier, BoxStatefulSupplier};
321 ///
322 /// let supplier = BoxStatefulSupplier::new(|| 42);
323 /// let mut closure = supplier.into_fn();
324 /// assert_eq!(closure(), 42);
325 /// assert_eq!(closure(), 42);
326 /// ```
327 ///
328 /// ## Using with functions that expect FnMut
329 ///
330 /// ```rust
331 /// use qubit_function::{Supplier, BoxStatefulSupplier};
332 ///
333 /// fn call_fn_twice<F: FnMut() -> i32>(mut f: F) -> (i32, i32) {
334 /// (f(), f())
335 /// }
336 ///
337 /// let supplier = BoxStatefulSupplier::new(|| 100);
338 /// let closure = supplier.into_fn();
339 /// assert_eq!(call_fn_twice(closure), (100, 100));
340 /// ```
341 fn into_fn(mut self) -> impl FnMut() -> T
342 where
343 Self: Sized + 'static,
344 {
345 move || self.get()
346 }
347
348 /// Converts to `BoxSupplierOnce`.
349 ///
350 /// This method has a default implementation that wraps the
351 /// supplier in a `BoxSupplierOnce`. Custom implementations
352 /// can override this method for optimization purposes.
353 ///
354 /// # Returns
355 ///
356 /// A new `BoxSupplierOnce<T>` instance
357 ///
358 /// # Examples
359 ///
360 /// ```rust
361 /// use qubit_function::StatefulSupplier;
362 ///
363 /// let closure = || 42;
364 /// let once = closure.into_once();
365 /// assert_eq!(once.get(), 42);
366 /// ```
367 fn into_once(mut self) -> BoxSupplierOnce<T>
368 where
369 Self: Sized + 'static,
370 T: 'static,
371 {
372 BoxSupplierOnce::new(move || self.get())
373 }
374
375 /// Creates a `BoxStatefulSupplier` from a cloned supplier.
376 ///
377 /// Uses `Clone` to obtain an owned copy and converts it into a
378 /// `BoxStatefulSupplier`. Implementations can override this for a more
379 /// efficient conversion.
380 fn to_box(&self) -> BoxStatefulSupplier<T>
381 where
382 Self: Clone + Sized + 'static,
383 T: 'static,
384 {
385 self.clone().into_box()
386 }
387
388 /// Creates an `RcStatefulSupplier` from a cloned supplier.
389 ///
390 /// Uses `Clone` to obtain an owned copy and converts it into an
391 /// `RcStatefulSupplier`. Implementations can override it for better
392 /// performance.
393 fn to_rc(&self) -> RcStatefulSupplier<T>
394 where
395 Self: Clone + Sized + 'static,
396 T: 'static,
397 {
398 self.clone().into_rc()
399 }
400
401 /// Creates an `ArcStatefulSupplier` from a cloned supplier.
402 ///
403 /// Requires the supplier and produced values to be `Send` so the
404 /// resulting supplier can be shared across threads.
405 fn to_arc(&self) -> ArcStatefulSupplier<T>
406 where
407 Self: Clone + Sized + Send + 'static,
408 T: 'static,
409 {
410 self.clone().into_arc()
411 }
412
413 /// Creates a closure from a cloned supplier.
414 ///
415 /// The default implementation clones `self` and consumes the clone
416 /// to produce a closure. Concrete suppliers can override it to
417 /// avoid the additional clone.
418 fn to_fn(&self) -> impl FnMut() -> T
419 where
420 Self: Clone + Sized + 'static,
421 {
422 self.clone().into_fn()
423 }
424
425 /// Creates a `BoxSupplierOnce` from a cloned supplier
426 ///
427 /// Uses `Clone` to obtain an owned copy and converts it into a
428 /// `BoxSupplierOnce`. Requires `Self: Clone`. Custom implementations
429 /// can override this for better performance.
430 fn to_once(&self) -> BoxSupplierOnce<T>
431 where
432 Self: Clone + Sized + 'static,
433 T: 'static,
434 {
435 self.clone().into_once()
436 }
437}
438
439// ==========================================================================
440// BoxStatefulSupplier - Single Ownership Implementation
441// ==========================================================================
442
443/// Box-based single ownership supplier.
444///
445/// Uses `Box<dyn FnMut() -> T>` for single ownership scenarios.
446/// This is the most lightweight supplier with zero reference
447/// counting overhead.
448///
449/// # Ownership Model
450///
451/// Methods consume `self` (move semantics). When you call a method
452/// like `map()`, the original supplier is consumed and you get a new
453/// one:
454///
455/// ```rust
456/// use qubit_function::{BoxStatefulSupplier, Supplier};
457///
458/// let supplier = BoxStatefulSupplier::new(|| 10);
459/// let mapped = supplier.map(|x| x * 2);
460/// // supplier is no longer usable here
461/// ```
462///
463/// # Examples
464///
465/// ## Counter
466///
467/// ```rust
468/// use qubit_function::{BoxStatefulSupplier, Supplier};
469///
470/// let mut counter = 0;
471/// let mut supplier = BoxStatefulSupplier::new(move || {
472/// counter += 1;
473/// counter
474/// });
475///
476/// assert_eq!(supplier.get(), 1);
477/// assert_eq!(supplier.get(), 2);
478/// ```
479///
480/// ## Method Chaining
481///
482/// ```rust
483/// use qubit_function::{BoxStatefulSupplier, Supplier};
484///
485/// let mut pipeline = BoxStatefulSupplier::new(|| 10)
486/// .map(|x| x * 2)
487/// .map(|x| x + 5);
488///
489/// assert_eq!(pipeline.get(), 25);
490/// ```
491///
492/// # Author
493///
494/// Haixing Hu
495pub struct BoxStatefulSupplier<T> {
496 function: Box<dyn FnMut() -> T>,
497 name: Option<String>,
498}
499
500impl<T> BoxStatefulSupplier<T>
501where
502 T: 'static,
503{
504 // Generates: new(), new_with_name(), name(), set_name(), constant()
505 impl_supplier_common_methods!(BoxStatefulSupplier<T>, (FnMut() -> T + 'static), |f| {
506 Box::new(f)
507 });
508
509 // Generates: map(), filter(), zip()
510 impl_box_supplier_methods!(BoxStatefulSupplier<T>, StatefulSupplier);
511
512 /// Creates a memoizing supplier.
513 ///
514 /// Returns a new supplier that caches the first value it
515 /// produces. All subsequent calls return the cached value.
516 ///
517 /// # Returns
518 ///
519 /// A new memoized `BoxStatefulSupplier<T>`
520 ///
521 /// # Examples
522 ///
523 /// ```rust
524 /// use qubit_function::{BoxStatefulSupplier, Supplier};
525 ///
526 /// let mut call_count = 0;
527 /// let mut memoized = BoxStatefulSupplier::new(move || {
528 /// call_count += 1;
529 /// 42
530 /// }).memoize();
531 ///
532 /// assert_eq!(memoized.get(), 42); // Calls underlying function
533 /// assert_eq!(memoized.get(), 42); // Returns cached value
534 /// ```
535 pub fn memoize(mut self) -> BoxStatefulSupplier<T>
536 where
537 T: Clone + 'static,
538 {
539 let mut cache: Option<T> = None;
540 BoxStatefulSupplier::new(move || {
541 if let Some(ref cached) = cache {
542 cached.clone()
543 } else {
544 let value = StatefulSupplier::get(&mut self);
545 cache = Some(value.clone());
546 value
547 }
548 })
549 }
550}
551
552// Generates: Debug and Display implementations for BoxStatefulSupplier<T>
553impl_supplier_debug_display!(BoxStatefulSupplier<T>);
554
555impl<T> StatefulSupplier<T> for BoxStatefulSupplier<T> {
556 fn get(&mut self) -> T {
557 (self.function)()
558 }
559
560 // Generates: into_box(), into_rc(), into_fn(), into_once()
561 impl_box_conversions!(
562 BoxStatefulSupplier<T>,
563 RcStatefulSupplier,
564 FnMut() -> T,
565 BoxSupplierOnce
566 );
567}
568
569// ==========================================================================
570// RcStatefulSupplier - Single-threaded Shared Ownership Implementation
571// ==========================================================================
572
573/// Single-threaded shared ownership supplier.
574///
575/// Uses `Rc<RefCell<dyn FnMut() -> T>>` for single-threaded shared
576/// ownership. Can be cloned but not sent across threads.
577///
578/// # Ownership Model
579///
580/// Like `ArcStatefulSupplier`, methods borrow `&self` instead of consuming
581/// `self`:
582///
583/// ```rust
584/// use qubit_function::{RcStatefulSupplier, Supplier};
585///
586/// let source = RcStatefulSupplier::new(|| 10);
587/// let mapped = source.map(|x| x * 2);
588/// // source is still usable here!
589/// ```
590///
591/// # Examples
592///
593/// ## Shared Counter
594///
595/// ```rust
596/// use qubit_function::{RcStatefulSupplier, Supplier};
597/// use std::rc::Rc;
598/// use std::cell::RefCell;
599///
600/// let counter = Rc::new(RefCell::new(0));
601/// let counter_clone = Rc::clone(&counter);
602///
603/// let supplier = RcStatefulSupplier::new(move || {
604/// let mut c = counter_clone.borrow_mut();
605/// *c += 1;
606/// *c
607/// });
608///
609/// let mut s1 = supplier.clone();
610/// let mut s2 = supplier.clone();
611/// assert_eq!(s1.get(), 1);
612/// assert_eq!(s2.get(), 2);
613/// ```
614///
615/// ## Reusable Transformations
616///
617/// ```rust
618/// use qubit_function::{RcStatefulSupplier, Supplier};
619///
620/// let base = RcStatefulSupplier::new(|| 10);
621/// let doubled = base.map(|x| x * 2);
622/// let tripled = base.map(|x| x * 3);
623///
624/// let mut b = base;
625/// let mut d = doubled;
626/// let mut t = tripled;
627/// assert_eq!(b.get(), 10);
628/// assert_eq!(d.get(), 20);
629/// assert_eq!(t.get(), 30);
630/// ```
631///
632/// # Author
633///
634/// Haixing Hu
635pub struct RcStatefulSupplier<T> {
636 function: Rc<RefCell<dyn FnMut() -> T>>,
637 name: Option<String>,
638}
639
640impl<T> RcStatefulSupplier<T>
641where
642 T: 'static,
643{
644 // Generates: new(), new_with_name(), name(), set_name(), constant()
645 impl_supplier_common_methods!(
646 RcStatefulSupplier<T>,
647 (FnMut() -> T + 'static),
648 |f| Rc::new(RefCell::new(f))
649 );
650
651 // Generates: map(), filter(), zip()
652 impl_shared_supplier_methods!(
653 RcStatefulSupplier<T>,
654 StatefulSupplier,
655 ('static)
656 );
657
658 /// Creates a memoizing supplier.
659 ///
660 /// # Returns
661 ///
662 /// A new memoized `RcStatefulSupplier<T>`
663 ///
664 /// # Examples
665 ///
666 /// ```rust
667 /// use qubit_function::{RcStatefulSupplier, Supplier};
668 /// use std::rc::Rc;
669 /// use std::cell::RefCell;
670 ///
671 /// let call_count = Rc::new(RefCell::new(0));
672 /// let call_count_clone = Rc::clone(&call_count);
673 /// let source = RcStatefulSupplier::new(move || {
674 /// let mut c = call_count_clone.borrow_mut();
675 /// *c += 1;
676 /// 42
677 /// });
678 /// let memoized = source.memoize();
679 ///
680 /// let mut s = memoized;
681 /// assert_eq!(s.get(), 42); // Calls underlying function
682 /// assert_eq!(s.get(), 42); // Returns cached value
683 /// assert_eq!(*call_count.borrow(), 1);
684 /// ```
685 pub fn memoize(&self) -> RcStatefulSupplier<T>
686 where
687 T: Clone + 'static,
688 {
689 let self_fn = Rc::clone(&self.function);
690 let cache: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
691 RcStatefulSupplier {
692 function: Rc::new(RefCell::new(move || {
693 let mut cache_ref = cache.borrow_mut();
694 if let Some(ref cached) = *cache_ref {
695 cached.clone()
696 } else {
697 let value = self_fn.borrow_mut()();
698 *cache_ref = Some(value.clone());
699 value
700 }
701 })),
702 name: None,
703 }
704 }
705}
706
707// Generates: Debug and Display implementations for RcStatefulSupplier<T>
708impl_supplier_debug_display!(RcStatefulSupplier<T>);
709
710// Generates: Clone implementation for RcStatefulSupplier<T>
711impl_supplier_clone!(RcStatefulSupplier<T>);
712
713impl<T> StatefulSupplier<T> for RcStatefulSupplier<T> {
714 fn get(&mut self) -> T {
715 (self.function.borrow_mut())()
716 }
717
718 // Generate all conversion methods using the unified macro
719 impl_rc_conversions!(
720 RcStatefulSupplier<T>,
721 BoxStatefulSupplier,
722 BoxSupplierOnce,
723 FnMut() -> T
724 );
725}
726
727// ==========================================================================
728// ArcStatefulSupplier - Thread-safe Shared Ownership Implementation
729// ==========================================================================
730
731/// Thread-safe shared ownership supplier.
732///
733/// Uses `Arc<Mutex<dyn FnMut() -> T + Send>>` for thread-safe
734/// shared ownership. Can be cloned and sent across threads.
735///
736/// # Ownership Model
737///
738/// Methods borrow `&self` instead of consuming `self`. The original
739/// supplier remains usable after method calls:
740///
741/// ```rust
742/// use qubit_function::{ArcStatefulSupplier, Supplier};
743///
744/// let source = ArcStatefulSupplier::new(|| 10);
745/// let mapped = source.map(|x| x * 2);
746/// // source is still usable here!
747/// ```
748///
749/// # Examples
750///
751/// ## Thread-safe Counter
752///
753/// ```rust
754/// use qubit_function::{ArcStatefulSupplier, Supplier};
755/// use std::sync::{Arc, Mutex};
756/// use std::thread;
757///
758/// let counter = Arc::new(Mutex::new(0));
759/// let counter_clone = Arc::clone(&counter);
760///
761/// let supplier = ArcStatefulSupplier::new(move || {
762/// let mut c = counter_clone.lock().unwrap();
763/// *c += 1;
764/// *c
765/// });
766///
767/// let mut s1 = supplier.clone();
768/// let mut s2 = supplier.clone();
769///
770/// let h1 = thread::spawn(move || s1.get());
771/// let h2 = thread::spawn(move || s2.get());
772///
773/// let v1 = h1.join().unwrap();
774/// let v2 = h2.join().unwrap();
775/// assert!(v1 != v2);
776/// ```
777///
778/// ## Reusable Transformations
779///
780/// ```rust
781/// use qubit_function::{ArcStatefulSupplier, Supplier};
782///
783/// let base = ArcStatefulSupplier::new(|| 10);
784/// let doubled = base.map(|x| x * 2);
785/// let tripled = base.map(|x| x * 3);
786///
787/// // All remain usable
788/// let mut b = base;
789/// let mut d = doubled;
790/// let mut t = tripled;
791/// assert_eq!(b.get(), 10);
792/// assert_eq!(d.get(), 20);
793/// assert_eq!(t.get(), 30);
794/// ```
795///
796/// # Author
797///
798/// Haixing Hu
799pub struct ArcStatefulSupplier<T> {
800 function: Arc<Mutex<dyn FnMut() -> T + Send>>,
801 name: Option<String>,
802}
803
804impl<T> ArcStatefulSupplier<T>
805where
806 T: 'static,
807{
808 // Generates: new(), new_with_name(), name(), set_name()
809 // Note: constant() is NOT generated here, implemented separately below
810 crate::macros::impl_common_new_methods!(
811 (FnMut() -> T + Send + 'static),
812 |f| Arc::new(Mutex::new(f)),
813 "supplier"
814 );
815
816 crate::macros::impl_common_name_methods!("supplier");
817
818 // Generates: map(), filter(), zip()
819 impl_shared_supplier_methods!(ArcStatefulSupplier<T>, StatefulSupplier, (arc));
820}
821
822// Separate impl block for constant() and memoize() with stricter T: Send bound
823impl<T> ArcStatefulSupplier<T>
824where
825 T: Send + 'static,
826{
827 /// Creates a supplier that returns a constant value.
828 ///
829 /// Creates a supplier that always returns the same value. Useful for
830 /// default values or placeholder implementations.
831 ///
832 /// **Note:** This method requires `T: Send` because the constant value
833 /// is captured by a `FnMut` closure which will be stored in an `Arc<Mutex<...>>`.
834 ///
835 /// # Parameters
836 ///
837 /// * `value` - The constant value to return
838 ///
839 /// # Returns
840 ///
841 /// Returns a new supplier instance that returns the constant value.
842 ///
843 /// # Examples
844 ///
845 /// ```rust
846 /// use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
847 ///
848 /// let mut supplier = ArcStatefulSupplier::constant(42);
849 /// assert_eq!(supplier.get(), 42);
850 /// assert_eq!(supplier.get(), 42); // Can be called multiple times
851 /// ```
852 pub fn constant(value: T) -> Self
853 where
854 T: Clone,
855 {
856 Self::new(move || value.clone())
857 }
858
859 /// Creates a memoizing supplier.
860 ///
861 /// **Note:** This method requires `T: Send` because the cached value
862 /// needs to be shared across threads via `Arc<Mutex<...>>`.
863 ///
864 /// # Returns
865 ///
866 /// A new memoized `ArcStatefulSupplier<T>`
867 ///
868 /// # Examples
869 ///
870 /// ```rust
871 /// use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
872 /// use std::sync::{Arc, Mutex};
873 ///
874 /// let call_count = Arc::new(Mutex::new(0));
875 /// let call_count_clone = Arc::clone(&call_count);
876 /// let source = ArcStatefulSupplier::new(move || {
877 /// let mut c = call_count_clone.lock();
878 /// *c += 1;
879 /// 42
880 /// });
881 /// let memoized = source.memoize();
882 ///
883 /// let mut s = memoized;
884 /// assert_eq!(s.get(), 42); // Calls underlying function
885 /// assert_eq!(s.get(), 42); // Returns cached value
886 /// assert_eq!(*call_count.lock(), 1);
887 /// ```
888 pub fn memoize(&self) -> ArcStatefulSupplier<T>
889 where
890 T: Clone,
891 {
892 let self_fn = Arc::clone(&self.function);
893 let cache: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
894 ArcStatefulSupplier {
895 function: Arc::new(Mutex::new(move || {
896 let mut cache_guard = cache.lock();
897 if let Some(ref cached) = *cache_guard {
898 cached.clone()
899 } else {
900 let value = self_fn.lock()();
901 *cache_guard = Some(value.clone());
902 value
903 }
904 })),
905 name: None,
906 }
907 }
908}
909
910// Generates: Debug and Display implementations for ArcStatefulSupplier<T>
911impl_supplier_debug_display!(ArcStatefulSupplier<T>);
912
913// Generates: Clone implementation for ArcStatefulSupplier<T>
914impl_supplier_clone!(ArcStatefulSupplier<T>);
915
916impl<T> StatefulSupplier<T> for ArcStatefulSupplier<T> {
917 fn get(&mut self) -> T {
918 (self.function.lock())()
919 }
920
921 // Use macro to implement conversion methods
922 impl_arc_conversions!(
923 ArcStatefulSupplier<T>,
924 BoxStatefulSupplier,
925 RcStatefulSupplier,
926 BoxSupplierOnce,
927 FnMut() -> T
928 );
929}
930
931// ==========================================================================
932// Implement StatefulSupplier for Closures
933// ==========================================================================
934
935// Implement StatefulSupplier<T> for any type that implements FnMut() -> T
936impl_closure_trait!(
937 StatefulSupplier<T>,
938 get,
939 BoxSupplierOnce,
940 FnMut() -> T
941);
942
943// ==========================================================================
944// Extension Trait for Closure Operations
945// ==========================================================================
946
947/// Extension trait providing supplier operations for closures
948///
949/// Provides composition methods (`map`, `filter`, `zip`, `memoize`) for
950/// closures implementing `FnMut() -> T` without requiring explicit
951/// wrapping in `BoxStatefulSupplier`.
952///
953/// This trait is automatically implemented for all closures and function
954/// pointers that implement `FnMut() -> T`.
955///
956/// # Design Rationale
957///
958/// While closures automatically implement `Supplier<T>` through blanket
959/// implementation, they don't have access to instance methods like
960/// `map`, `filter`, and `zip`. This extension trait provides those
961/// methods, returning `BoxStatefulSupplier` for maximum flexibility.
962///
963/// # Examples
964///
965/// ## Map transformation
966///
967/// ```rust
968/// use qubit_function::{Supplier, FnStatefulSupplierOps};
969///
970/// let mut counter = 0;
971/// let mut mapped = (move || {
972/// counter += 1;
973/// counter
974/// }).map(|x| x * 2);
975///
976/// assert_eq!(mapped.get(), 2);
977/// assert_eq!(mapped.get(), 4);
978/// ```
979///
980/// ## Filter values
981///
982/// ```rust
983/// use qubit_function::{Supplier, FnStatefulSupplierOps};
984///
985/// let mut counter = 0;
986/// let mut filtered = (move || {
987/// counter += 1;
988/// counter
989/// }).filter(|x| x % 2 == 0);
990///
991/// assert_eq!(filtered.get(), None); // 1 is odd
992/// assert_eq!(filtered.get(), Some(2)); // 2 is even
993/// ```
994///
995/// ## Combine with zip
996///
997/// ```rust
998/// use qubit_function::{Supplier, FnStatefulSupplierOps, BoxStatefulSupplier};
999///
1000/// let first = || 42;
1001/// let second = BoxStatefulSupplier::new(|| "hello");
1002/// let mut zipped = first.zip(second);
1003///
1004/// assert_eq!(zipped.get(), (42, "hello"));
1005/// ```
1006///
1007/// # Author
1008///
1009/// Haixing Hu
1010pub trait FnStatefulSupplierOps<T>: FnMut() -> T + Sized + 'static {
1011 /// Maps the output using a transformation function.
1012 ///
1013 /// Consumes the closure and returns a new supplier that applies
1014 /// the mapper to each output.
1015 ///
1016 /// # Parameters
1017 ///
1018 /// * `mapper` - The mapper to apply to the output
1019 ///
1020 /// # Returns
1021 ///
1022 /// A new mapped `BoxStatefulSupplier<U>`
1023 ///
1024 /// # Examples
1025 ///
1026 /// ```rust
1027 /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1028 ///
1029 /// let mut mapped = (|| 10)
1030 /// .map(|x| x * 2)
1031 /// .map(|x| x + 5);
1032 /// assert_eq!(mapped.get(), 25);
1033 /// ```
1034 fn map<U, M>(self, mapper: M) -> BoxStatefulSupplier<U>
1035 where
1036 M: Transformer<T, U> + 'static,
1037 U: 'static,
1038 T: 'static,
1039 {
1040 BoxStatefulSupplier::new(self).map(mapper)
1041 }
1042
1043 /// Filters output based on a predicate.
1044 ///
1045 /// Returns a new supplier that returns `Some(value)` if the
1046 /// predicate is satisfied, `None` otherwise.
1047 ///
1048 /// # Parameters
1049 ///
1050 /// * `predicate` - The predicate to test the supplied value
1051 ///
1052 /// # Returns
1053 ///
1054 /// A new filtered `BoxStatefulSupplier<Option<T>>`
1055 ///
1056 /// # Examples
1057 ///
1058 /// ```rust
1059 /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1060 ///
1061 /// let mut counter = 0;
1062 /// let mut filtered = (move || {
1063 /// counter += 1;
1064 /// counter
1065 /// }).filter(|x| x % 2 == 0);
1066 ///
1067 /// assert_eq!(filtered.get(), None); // 1 is odd
1068 /// assert_eq!(filtered.get(), Some(2)); // 2 is even
1069 /// ```
1070 fn filter<P>(self, predicate: P) -> BoxStatefulSupplier<Option<T>>
1071 where
1072 P: Predicate<T> + 'static,
1073 T: 'static,
1074 {
1075 BoxStatefulSupplier::new(self).filter(predicate)
1076 }
1077
1078 /// Combines this supplier with another, producing a tuple.
1079 ///
1080 /// Consumes both suppliers and returns a new supplier that
1081 /// produces `(T, U)` tuples.
1082 ///
1083 /// # Parameters
1084 ///
1085 /// * `other` - The other supplier to combine with. Can be any type
1086 /// implementing `Supplier<U>`
1087 ///
1088 /// # Returns
1089 ///
1090 /// A new `BoxStatefulSupplier<(T, U)>`
1091 ///
1092 /// # Examples
1093 ///
1094 /// ```rust
1095 /// use qubit_function::{Supplier, FnStatefulSupplierOps, BoxStatefulSupplier};
1096 ///
1097 /// let first = || 42;
1098 /// let second = BoxStatefulSupplier::new(|| "hello");
1099 /// let mut zipped = first.zip(second);
1100 ///
1101 /// assert_eq!(zipped.get(), (42, "hello"));
1102 /// ```
1103 fn zip<S, U>(self, other: S) -> BoxStatefulSupplier<(T, U)>
1104 where
1105 S: StatefulSupplier<U> + 'static,
1106 U: 'static,
1107 T: 'static,
1108 {
1109 BoxStatefulSupplier::new(self).zip(other)
1110 }
1111
1112 /// Creates a memoizing supplier.
1113 ///
1114 /// Returns a new supplier that caches the first value it
1115 /// produces. All subsequent calls return the cached value.
1116 ///
1117 /// # Returns
1118 ///
1119 /// A new memoized `BoxStatefulSupplier<T>`
1120 ///
1121 /// # Examples
1122 ///
1123 /// ```rust
1124 /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1125 ///
1126 /// let mut call_count = 0;
1127 /// let mut memoized = (move || {
1128 /// call_count += 1;
1129 /// 42
1130 /// }).memoize();
1131 ///
1132 /// assert_eq!(memoized.get(), 42); // Calls underlying function
1133 /// assert_eq!(memoized.get(), 42); // Returns cached value
1134 /// ```
1135 fn memoize(self) -> BoxStatefulSupplier<T>
1136 where
1137 T: Clone + 'static,
1138 {
1139 BoxStatefulSupplier::new(self).memoize()
1140 }
1141}
1142
1143// Implement the extension trait for all closures
1144impl<T, F> FnStatefulSupplierOps<T> for F where F: FnMut() -> T + Sized + 'static {}