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> {
501 // Generates: new(), new_with_name(), name(), set_name(), constant()
502 impl_supplier_common_methods!(BoxStatefulSupplier<T>, (FnMut() -> T + 'static), |f| {
503 Box::new(f)
504 });
505
506 // Generates: map(), filter(), zip()
507 impl_box_supplier_methods!(BoxStatefulSupplier<T>, StatefulSupplier);
508
509 /// Creates a memoizing supplier.
510 ///
511 /// Returns a new supplier that caches the first value it
512 /// produces. All subsequent calls return the cached value.
513 ///
514 /// # Returns
515 ///
516 /// A new memoized `BoxStatefulSupplier<T>`
517 ///
518 /// # Examples
519 ///
520 /// ```rust
521 /// use qubit_function::{BoxStatefulSupplier, Supplier};
522 ///
523 /// let mut call_count = 0;
524 /// let mut memoized = BoxStatefulSupplier::new(move || {
525 /// call_count += 1;
526 /// 42
527 /// }).memoize();
528 ///
529 /// assert_eq!(memoized.get(), 42); // Calls underlying function
530 /// assert_eq!(memoized.get(), 42); // Returns cached value
531 /// ```
532 pub fn memoize(mut self) -> BoxStatefulSupplier<T>
533 where
534 T: Clone + 'static,
535 {
536 let mut cache: Option<T> = None;
537 BoxStatefulSupplier::new(move || {
538 if let Some(ref cached) = cache {
539 cached.clone()
540 } else {
541 let value = StatefulSupplier::get(&mut self);
542 cache = Some(value.clone());
543 value
544 }
545 })
546 }
547}
548
549// Generates: Debug and Display implementations for BoxStatefulSupplier<T>
550impl_supplier_debug_display!(BoxStatefulSupplier<T>);
551
552impl<T> StatefulSupplier<T> for BoxStatefulSupplier<T> {
553 fn get(&mut self) -> T {
554 (self.function)()
555 }
556
557 // Generates: into_box(), into_rc(), into_fn(), into_once()
558 impl_box_conversions!(
559 BoxStatefulSupplier<T>,
560 RcStatefulSupplier,
561 FnMut() -> T,
562 BoxSupplierOnce
563 );
564}
565
566// ==========================================================================
567// RcStatefulSupplier - Single-threaded Shared Ownership Implementation
568// ==========================================================================
569
570/// Single-threaded shared ownership supplier.
571///
572/// Uses `Rc<RefCell<dyn FnMut() -> T>>` for single-threaded shared
573/// ownership. Can be cloned but not sent across threads.
574///
575/// # Ownership Model
576///
577/// Like `ArcStatefulSupplier`, methods borrow `&self` instead of consuming
578/// `self`:
579///
580/// ```rust
581/// use qubit_function::{RcStatefulSupplier, Supplier};
582///
583/// let source = RcStatefulSupplier::new(|| 10);
584/// let mapped = source.map(|x| x * 2);
585/// // source is still usable here!
586/// ```
587///
588/// # Examples
589///
590/// ## Shared Counter
591///
592/// ```rust
593/// use qubit_function::{RcStatefulSupplier, Supplier};
594/// use std::rc::Rc;
595/// use std::cell::RefCell;
596///
597/// let counter = Rc::new(RefCell::new(0));
598/// let counter_clone = Rc::clone(&counter);
599///
600/// let supplier = RcStatefulSupplier::new(move || {
601/// let mut c = counter_clone.borrow_mut();
602/// *c += 1;
603/// *c
604/// });
605///
606/// let mut s1 = supplier.clone();
607/// let mut s2 = supplier.clone();
608/// assert_eq!(s1.get(), 1);
609/// assert_eq!(s2.get(), 2);
610/// ```
611///
612/// ## Reusable Transformations
613///
614/// ```rust
615/// use qubit_function::{RcStatefulSupplier, Supplier};
616///
617/// let base = RcStatefulSupplier::new(|| 10);
618/// let doubled = base.map(|x| x * 2);
619/// let tripled = base.map(|x| x * 3);
620///
621/// let mut b = base;
622/// let mut d = doubled;
623/// let mut t = tripled;
624/// assert_eq!(b.get(), 10);
625/// assert_eq!(d.get(), 20);
626/// assert_eq!(t.get(), 30);
627/// ```
628///
629/// # Author
630///
631/// Haixing Hu
632pub struct RcStatefulSupplier<T> {
633 function: Rc<RefCell<dyn FnMut() -> T>>,
634 name: Option<String>,
635}
636
637impl<T> RcStatefulSupplier<T> {
638 // Generates: new(), new_with_name(), name(), set_name(), constant()
639 impl_supplier_common_methods!(
640 RcStatefulSupplier<T>,
641 (FnMut() -> T + 'static),
642 |f| Rc::new(RefCell::new(f))
643 );
644
645 // Generates: map(), filter(), zip()
646 impl_shared_supplier_methods!(
647 RcStatefulSupplier<T>,
648 StatefulSupplier,
649 ('static)
650 );
651
652 /// Creates a memoizing supplier.
653 ///
654 /// # Returns
655 ///
656 /// A new memoized `RcStatefulSupplier<T>`
657 ///
658 /// # Examples
659 ///
660 /// ```rust
661 /// use qubit_function::{RcStatefulSupplier, Supplier};
662 /// use std::rc::Rc;
663 /// use std::cell::RefCell;
664 ///
665 /// let call_count = Rc::new(RefCell::new(0));
666 /// let call_count_clone = Rc::clone(&call_count);
667 /// let source = RcStatefulSupplier::new(move || {
668 /// let mut c = call_count_clone.borrow_mut();
669 /// *c += 1;
670 /// 42
671 /// });
672 /// let memoized = source.memoize();
673 ///
674 /// let mut s = memoized;
675 /// assert_eq!(s.get(), 42); // Calls underlying function
676 /// assert_eq!(s.get(), 42); // Returns cached value
677 /// assert_eq!(*call_count.borrow(), 1);
678 /// ```
679 pub fn memoize(&self) -> RcStatefulSupplier<T>
680 where
681 T: Clone + 'static,
682 {
683 let self_fn = Rc::clone(&self.function);
684 let cache: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
685 RcStatefulSupplier {
686 function: Rc::new(RefCell::new(move || {
687 let mut cache_ref = cache.borrow_mut();
688 if let Some(ref cached) = *cache_ref {
689 cached.clone()
690 } else {
691 let value = self_fn.borrow_mut()();
692 *cache_ref = Some(value.clone());
693 value
694 }
695 })),
696 name: None,
697 }
698 }
699}
700
701// Generates: Debug and Display implementations for RcStatefulSupplier<T>
702impl_supplier_debug_display!(RcStatefulSupplier<T>);
703
704// Generates: Clone implementation for RcStatefulSupplier<T>
705impl_supplier_clone!(RcStatefulSupplier<T>);
706
707impl<T> StatefulSupplier<T> for RcStatefulSupplier<T> {
708 fn get(&mut self) -> T {
709 (self.function.borrow_mut())()
710 }
711
712 // Generate all conversion methods using the unified macro
713 impl_rc_conversions!(
714 RcStatefulSupplier<T>,
715 BoxStatefulSupplier,
716 BoxSupplierOnce,
717 FnMut() -> T
718 );
719}
720
721// ==========================================================================
722// ArcStatefulSupplier - Thread-safe Shared Ownership Implementation
723// ==========================================================================
724
725/// Thread-safe shared ownership supplier.
726///
727/// Uses `Arc<Mutex<dyn FnMut() -> T + Send>>` for thread-safe
728/// shared ownership. Can be cloned and sent across threads.
729///
730/// # Ownership Model
731///
732/// Methods borrow `&self` instead of consuming `self`. The original
733/// supplier remains usable after method calls:
734///
735/// ```rust
736/// use qubit_function::{ArcStatefulSupplier, Supplier};
737///
738/// let source = ArcStatefulSupplier::new(|| 10);
739/// let mapped = source.map(|x| x * 2);
740/// // source is still usable here!
741/// ```
742///
743/// # Examples
744///
745/// ## Thread-safe Counter
746///
747/// ```rust
748/// use qubit_function::{ArcStatefulSupplier, Supplier};
749/// use std::sync::{Arc, Mutex};
750/// use std::thread;
751///
752/// let counter = Arc::new(Mutex::new(0));
753/// let counter_clone = Arc::clone(&counter);
754///
755/// let supplier = ArcStatefulSupplier::new(move || {
756/// let mut c = counter_clone.lock().unwrap();
757/// *c += 1;
758/// *c
759/// });
760///
761/// let mut s1 = supplier.clone();
762/// let mut s2 = supplier.clone();
763///
764/// let h1 = thread::spawn(move || s1.get());
765/// let h2 = thread::spawn(move || s2.get());
766///
767/// let v1 = h1.join().unwrap();
768/// let v2 = h2.join().unwrap();
769/// assert!(v1 != v2);
770/// ```
771///
772/// ## Reusable Transformations
773///
774/// ```rust
775/// use qubit_function::{ArcStatefulSupplier, Supplier};
776///
777/// let base = ArcStatefulSupplier::new(|| 10);
778/// let doubled = base.map(|x| x * 2);
779/// let tripled = base.map(|x| x * 3);
780///
781/// // All remain usable
782/// let mut b = base;
783/// let mut d = doubled;
784/// let mut t = tripled;
785/// assert_eq!(b.get(), 10);
786/// assert_eq!(d.get(), 20);
787/// assert_eq!(t.get(), 30);
788/// ```
789///
790/// # Author
791///
792/// Haixing Hu
793pub struct ArcStatefulSupplier<T> {
794 function: Arc<Mutex<dyn FnMut() -> T + Send>>,
795 name: Option<String>,
796}
797
798impl<T> ArcStatefulSupplier<T> {
799 // Generates: new(), new_with_name(), name(), set_name()
800 // Note: constant() is NOT generated here, implemented separately below
801 crate::macros::impl_common_new_methods!(
802 (FnMut() -> T + Send + 'static),
803 |f| Arc::new(Mutex::new(f)),
804 "supplier"
805 );
806
807 crate::macros::impl_common_name_methods!("supplier");
808
809 // Generates: map(), filter(), zip()
810 impl_shared_supplier_methods!(ArcStatefulSupplier<T>, StatefulSupplier, (arc));
811}
812
813// Separate impl block for constant() and memoize() with stricter T: Send bound
814impl<T> ArcStatefulSupplier<T> {
815 /// Creates a supplier that returns a constant value.
816 ///
817 /// Creates a supplier that always returns the same value. Useful for
818 /// default values or placeholder implementations.
819 ///
820 /// **Note:** This method requires `T: Send` because the constant value
821 /// is captured by a `FnMut` closure which will be stored in an `Arc<Mutex<...>>`.
822 ///
823 /// # Parameters
824 ///
825 /// * `value` - The constant value to return
826 ///
827 /// # Returns
828 ///
829 /// Returns a new supplier instance that returns the constant value.
830 ///
831 /// # Examples
832 ///
833 /// ```rust
834 /// use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
835 ///
836 /// let mut supplier = ArcStatefulSupplier::constant(42);
837 /// assert_eq!(supplier.get(), 42);
838 /// assert_eq!(supplier.get(), 42); // Can be called multiple times
839 /// ```
840 pub fn constant(value: T) -> Self
841 where
842 T: Clone + Send + 'static,
843 {
844 Self::new(move || value.clone())
845 }
846
847 /// Creates a memoizing supplier.
848 ///
849 /// **Note:** This method requires `T: Send` because the cached value
850 /// needs to be shared across threads via `Arc<Mutex<...>>`.
851 ///
852 /// # Returns
853 ///
854 /// A new memoized `ArcStatefulSupplier<T>`
855 ///
856 /// # Examples
857 ///
858 /// ```rust
859 /// use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
860 /// use std::sync::{Arc, Mutex};
861 ///
862 /// let call_count = Arc::new(Mutex::new(0));
863 /// let call_count_clone = Arc::clone(&call_count);
864 /// let source = ArcStatefulSupplier::new(move || {
865 /// let mut c = call_count_clone.lock();
866 /// *c += 1;
867 /// 42
868 /// });
869 /// let memoized = source.memoize();
870 ///
871 /// let mut s = memoized;
872 /// assert_eq!(s.get(), 42); // Calls underlying function
873 /// assert_eq!(s.get(), 42); // Returns cached value
874 /// assert_eq!(*call_count.lock(), 1);
875 /// ```
876 pub fn memoize(&self) -> ArcStatefulSupplier<T>
877 where
878 T: Clone + Send + 'static,
879 {
880 let self_fn = Arc::clone(&self.function);
881 let cache: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
882 ArcStatefulSupplier {
883 function: Arc::new(Mutex::new(move || {
884 let mut cache_guard = cache.lock();
885 if let Some(ref cached) = *cache_guard {
886 cached.clone()
887 } else {
888 let value = self_fn.lock()();
889 *cache_guard = Some(value.clone());
890 value
891 }
892 })),
893 name: None,
894 }
895 }
896}
897
898// Generates: Debug and Display implementations for ArcStatefulSupplier<T>
899impl_supplier_debug_display!(ArcStatefulSupplier<T>);
900
901// Generates: Clone implementation for ArcStatefulSupplier<T>
902impl_supplier_clone!(ArcStatefulSupplier<T>);
903
904impl<T> StatefulSupplier<T> for ArcStatefulSupplier<T> {
905 fn get(&mut self) -> T {
906 (self.function.lock())()
907 }
908
909 // Use macro to implement conversion methods
910 impl_arc_conversions!(
911 ArcStatefulSupplier<T>,
912 BoxStatefulSupplier,
913 RcStatefulSupplier,
914 BoxSupplierOnce,
915 FnMut() -> T
916 );
917}
918
919// ==========================================================================
920// Implement StatefulSupplier for Closures
921// ==========================================================================
922
923// Implement StatefulSupplier<T> for any type that implements FnMut() -> T
924impl_closure_trait!(
925 StatefulSupplier<T>,
926 get,
927 BoxSupplierOnce,
928 FnMut() -> T
929);
930
931// ==========================================================================
932// Extension Trait for Closure Operations
933// ==========================================================================
934
935/// Extension trait providing supplier operations for closures
936///
937/// Provides composition methods (`map`, `filter`, `zip`, `memoize`) for
938/// closures implementing `FnMut() -> T` without requiring explicit
939/// wrapping in `BoxStatefulSupplier`.
940///
941/// This trait is automatically implemented for all closures and function
942/// pointers that implement `FnMut() -> T`.
943///
944/// # Design Rationale
945///
946/// While closures automatically implement `Supplier<T>` through blanket
947/// implementation, they don't have access to instance methods like
948/// `map`, `filter`, and `zip`. This extension trait provides those
949/// methods, returning `BoxStatefulSupplier` for maximum flexibility.
950///
951/// # Examples
952///
953/// ## Map transformation
954///
955/// ```rust
956/// use qubit_function::{Supplier, FnStatefulSupplierOps};
957///
958/// let mut counter = 0;
959/// let mut mapped = (move || {
960/// counter += 1;
961/// counter
962/// }).map(|x| x * 2);
963///
964/// assert_eq!(mapped.get(), 2);
965/// assert_eq!(mapped.get(), 4);
966/// ```
967///
968/// ## Filter values
969///
970/// ```rust
971/// use qubit_function::{Supplier, FnStatefulSupplierOps};
972///
973/// let mut counter = 0;
974/// let mut filtered = (move || {
975/// counter += 1;
976/// counter
977/// }).filter(|x| x % 2 == 0);
978///
979/// assert_eq!(filtered.get(), None); // 1 is odd
980/// assert_eq!(filtered.get(), Some(2)); // 2 is even
981/// ```
982///
983/// ## Combine with zip
984///
985/// ```rust
986/// use qubit_function::{Supplier, FnStatefulSupplierOps, BoxStatefulSupplier};
987///
988/// let first = || 42;
989/// let second = BoxStatefulSupplier::new(|| "hello");
990/// let mut zipped = first.zip(second);
991///
992/// assert_eq!(zipped.get(), (42, "hello"));
993/// ```
994///
995/// # Author
996///
997/// Haixing Hu
998pub trait FnStatefulSupplierOps<T>: FnMut() -> T + Sized {
999 /// Maps the output using a transformation function.
1000 ///
1001 /// Consumes the closure and returns a new supplier that applies
1002 /// the mapper to each output.
1003 ///
1004 /// # Parameters
1005 ///
1006 /// * `mapper` - The mapper to apply to the output
1007 ///
1008 /// # Returns
1009 ///
1010 /// A new mapped `BoxStatefulSupplier<U>`
1011 ///
1012 /// # Examples
1013 ///
1014 /// ```rust
1015 /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1016 ///
1017 /// let mut mapped = (|| 10)
1018 /// .map(|x| x * 2)
1019 /// .map(|x| x + 5);
1020 /// assert_eq!(mapped.get(), 25);
1021 /// ```
1022 fn map<U, M>(self, mapper: M) -> BoxStatefulSupplier<U>
1023 where
1024 Self: 'static,
1025 M: Transformer<T, U> + 'static,
1026 U: 'static,
1027 T: 'static,
1028 {
1029 BoxStatefulSupplier::new(self).map(mapper)
1030 }
1031
1032 /// Filters output based on a predicate.
1033 ///
1034 /// Returns a new supplier that returns `Some(value)` if the
1035 /// predicate is satisfied, `None` otherwise.
1036 ///
1037 /// # Parameters
1038 ///
1039 /// * `predicate` - The predicate to test the supplied value
1040 ///
1041 /// # Returns
1042 ///
1043 /// A new filtered `BoxStatefulSupplier<Option<T>>`
1044 ///
1045 /// # Examples
1046 ///
1047 /// ```rust
1048 /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1049 ///
1050 /// let mut counter = 0;
1051 /// let mut filtered = (move || {
1052 /// counter += 1;
1053 /// counter
1054 /// }).filter(|x| x % 2 == 0);
1055 ///
1056 /// assert_eq!(filtered.get(), None); // 1 is odd
1057 /// assert_eq!(filtered.get(), Some(2)); // 2 is even
1058 /// ```
1059 fn filter<P>(self, predicate: P) -> BoxStatefulSupplier<Option<T>>
1060 where
1061 Self: 'static,
1062 P: Predicate<T> + 'static,
1063 T: 'static,
1064 {
1065 BoxStatefulSupplier::new(self).filter(predicate)
1066 }
1067
1068 /// Combines this supplier with another, producing a tuple.
1069 ///
1070 /// Consumes both suppliers and returns a new supplier that
1071 /// produces `(T, U)` tuples.
1072 ///
1073 /// # Parameters
1074 ///
1075 /// * `other` - The other supplier to combine with. Can be any type
1076 /// implementing `Supplier<U>`
1077 ///
1078 /// # Returns
1079 ///
1080 /// A new `BoxStatefulSupplier<(T, U)>`
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```rust
1085 /// use qubit_function::{Supplier, FnStatefulSupplierOps, BoxStatefulSupplier};
1086 ///
1087 /// let first = || 42;
1088 /// let second = BoxStatefulSupplier::new(|| "hello");
1089 /// let mut zipped = first.zip(second);
1090 ///
1091 /// assert_eq!(zipped.get(), (42, "hello"));
1092 /// ```
1093 fn zip<S, U>(self, other: S) -> BoxStatefulSupplier<(T, U)>
1094 where
1095 Self: 'static,
1096 S: StatefulSupplier<U> + 'static,
1097 U: 'static,
1098 T: 'static,
1099 {
1100 BoxStatefulSupplier::new(self).zip(other)
1101 }
1102
1103 /// Creates a memoizing supplier.
1104 ///
1105 /// Returns a new supplier that caches the first value it
1106 /// produces. All subsequent calls return the cached value.
1107 ///
1108 /// # Returns
1109 ///
1110 /// A new memoized `BoxStatefulSupplier<T>`
1111 ///
1112 /// # Examples
1113 ///
1114 /// ```rust
1115 /// use qubit_function::{Supplier, FnStatefulSupplierOps};
1116 ///
1117 /// let mut call_count = 0;
1118 /// let mut memoized = (move || {
1119 /// call_count += 1;
1120 /// 42
1121 /// }).memoize();
1122 ///
1123 /// assert_eq!(memoized.get(), 42); // Calls underlying function
1124 /// assert_eq!(memoized.get(), 42); // Returns cached value
1125 /// ```
1126 fn memoize(self) -> BoxStatefulSupplier<T>
1127 where
1128 Self: 'static,
1129 T: Clone + 'static,
1130 {
1131 BoxStatefulSupplier::new(self).memoize()
1132 }
1133}
1134
1135// Implement the extension trait for all closures
1136impl<T, F> FnStatefulSupplierOps<T> for F where F: FnMut() -> T + Sized {}