prism3_function/
supplier.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism 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//! - **`BoxSupplier<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//! - **`ArcSupplier<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//! - **`RcSupplier<T>`**: Single-threaded shared ownership using
45//!   `Rc<RefCell<dyn FnMut() -> T>>`. Can be cloned but not sent
46//!   across threads. Lower overhead than `ArcSupplier`.
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 prism3_function::{BoxSupplier, Supplier};
63//!
64//! let mut counter = 0;
65//! let mut supplier = BoxSupplier::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 prism3_function::{BoxSupplier, Supplier};
79//!
80//! let mut pipeline = BoxSupplier::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 prism3_function::{ArcSupplier, 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 = ArcSupplier::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
119
120use std::cell::RefCell;
121use std::rc::Rc;
122use std::sync::{Arc, Mutex};
123
124use crate::mapper::Mapper;
125
126// ==========================================================================
127// Supplier Trait
128// ==========================================================================
129
130/// Supplier trait: generates and returns values without input.
131///
132/// The core abstraction for value generation. Similar to Java's
133/// `Supplier<T>` interface, it produces values without taking any
134/// input parameters.
135///
136/// # Key Characteristics
137///
138/// - **No input parameters**: Pure value generation
139/// - **Mutable access**: Uses `&mut self` to allow state changes
140/// - **Returns ownership**: Returns `T` (not `&T`) to avoid lifetime
141///   issues
142/// - **Can modify state**: Commonly used for counters, sequences,
143///   and generators
144///
145/// # Automatically Implemented for Closures
146///
147/// All `FnMut() -> T` closures automatically implement this trait,
148/// enabling seamless integration with both raw closures and wrapped
149/// supplier types.
150///
151/// # Examples
152///
153/// ## Using with Generic Functions
154///
155/// ```rust
156/// use prism3_function::{Supplier, BoxSupplier};
157///
158/// fn call_twice<S: Supplier<i32>>(supplier: &mut S) -> (i32, i32) {
159///     (supplier.get(), supplier.get())
160/// }
161///
162/// let mut s = BoxSupplier::new(|| 42);
163/// assert_eq!(call_twice(&mut s), (42, 42));
164///
165/// let mut closure = || 100;
166/// assert_eq!(call_twice(&mut closure), (100, 100));
167/// ```
168///
169/// ## Stateful Supplier
170///
171/// ```rust
172/// use prism3_function::Supplier;
173///
174/// let mut counter = 0;
175/// let mut stateful = || {
176///     counter += 1;
177///     counter
178/// };
179///
180/// assert_eq!(stateful.get(), 1);
181/// assert_eq!(stateful.get(), 2);
182/// ```
183///
184/// # Author
185///
186/// Haixing Hu
187pub trait Supplier<T> {
188    /// Generates and returns the next value.
189    ///
190    /// Executes the underlying function and returns the generated
191    /// value. Uses `&mut self` because suppliers typically involve
192    /// state changes (counters, sequences, etc.).
193    ///
194    /// # Returns
195    ///
196    /// The generated value of type `T`
197    ///
198    /// # Examples
199    ///
200    /// ```rust
201    /// use prism3_function::{Supplier, BoxSupplier};
202    ///
203    /// let mut supplier = BoxSupplier::new(|| 42);
204    /// assert_eq!(supplier.get(), 42);
205    /// ```
206    fn get(&mut self) -> T;
207
208    /// Converts to `BoxSupplier`.
209    ///
210    /// This method has a default implementation that wraps the
211    /// supplier in a `BoxSupplier`. Custom implementations can
212    /// override this for more efficient conversions.
213    ///
214    /// # Returns
215    ///
216    /// A new `BoxSupplier<T>` instance
217    ///
218    /// # Examples
219    ///
220    /// ```rust
221    /// use prism3_function::Supplier;
222    ///
223    /// let closure = || 42;
224    /// let mut boxed = closure.into_box();
225    /// assert_eq!(boxed.get(), 42);
226    /// ```
227    fn into_box(mut self) -> BoxSupplier<T>
228    where
229        Self: Sized + 'static,
230        T: 'static,
231    {
232        BoxSupplier::new(move || self.get())
233    }
234
235    /// Converts to `RcSupplier`.
236    ///
237    /// This method has a default implementation that wraps the
238    /// supplier in an `RcSupplier`. Custom implementations can
239    /// override this for more efficient conversions.
240    ///
241    /// # Returns
242    ///
243    /// A new `RcSupplier<T>` instance
244    ///
245    /// # Examples
246    ///
247    /// ```rust
248    /// use prism3_function::Supplier;
249    ///
250    /// let closure = || 42;
251    /// let mut rc = closure.into_rc();
252    /// assert_eq!(rc.get(), 42);
253    /// ```
254    fn into_rc(mut self) -> RcSupplier<T>
255    where
256        Self: Sized + 'static,
257        T: 'static,
258    {
259        RcSupplier::new(move || self.get())
260    }
261
262    /// Converts to `ArcSupplier`.
263    ///
264    /// This method has a default implementation that wraps the
265    /// supplier in an `ArcSupplier`. Custom implementations can
266    /// override this for more efficient conversions.
267    ///
268    /// # Returns
269    ///
270    /// A new `ArcSupplier<T>` instance
271    ///
272    /// # Examples
273    ///
274    /// ```rust
275    /// use prism3_function::Supplier;
276    ///
277    /// let closure = || 42;
278    /// let mut arc = closure.into_arc();
279    /// assert_eq!(arc.get(), 42);
280    /// ```
281    fn into_arc(mut self) -> ArcSupplier<T>
282    where
283        Self: Sized + Send + 'static,
284        T: Send + 'static,
285    {
286        ArcSupplier::new(move || self.get())
287    }
288
289    /// Converts to a closure `FnMut() -> T`.
290    ///
291    /// This method wraps the supplier in a closure that calls the
292    /// `get()` method when invoked. This allows using suppliers
293    /// in contexts that expect `FnMut()` closures.
294    ///
295    /// # Returns
296    ///
297    /// A closure `impl FnMut() -> T`
298    ///
299    /// # Examples
300    ///
301    /// ```rust
302    /// use prism3_function::{Supplier, BoxSupplier};
303    ///
304    /// let supplier = BoxSupplier::new(|| 42);
305    /// let mut closure = supplier.into_fn();
306    /// assert_eq!(closure(), 42);
307    /// assert_eq!(closure(), 42);
308    /// ```
309    ///
310    /// ## Using with functions that expect FnMut
311    ///
312    /// ```rust
313    /// use prism3_function::{Supplier, BoxSupplier};
314    ///
315    /// fn call_fn_twice<F: FnMut() -> i32>(mut f: F) -> (i32, i32) {
316    ///     (f(), f())
317    /// }
318    ///
319    /// let supplier = BoxSupplier::new(|| 100);
320    /// let closure = supplier.into_fn();
321    /// assert_eq!(call_fn_twice(closure), (100, 100));
322    /// ```
323    fn into_fn(mut self) -> impl FnMut() -> T
324    where
325        Self: Sized,
326    {
327        move || self.get()
328    }
329
330    /// Creates a `BoxSupplier` from a cloned supplier.
331    ///
332    /// Uses `Clone` to obtain an owned copy and converts it into a
333    /// `BoxSupplier`. Implementations can override this for a more
334    /// efficient conversion.
335    fn to_box(&self) -> BoxSupplier<T>
336    where
337        Self: Clone + Sized + 'static,
338        T: 'static,
339    {
340        self.clone().into_box()
341    }
342
343    /// Creates an `RcSupplier` from a cloned supplier.
344    ///
345    /// Uses `Clone` to obtain an owned copy and converts it into an
346    /// `RcSupplier`. Implementations can override it for better
347    /// performance.
348    fn to_rc(&self) -> RcSupplier<T>
349    where
350        Self: Clone + Sized + 'static,
351        T: 'static,
352    {
353        self.clone().into_rc()
354    }
355
356    /// Creates an `ArcSupplier` from a cloned supplier.
357    ///
358    /// Requires the supplier and produced values to be `Send` so the
359    /// resulting supplier can be shared across threads.
360    fn to_arc(&self) -> ArcSupplier<T>
361    where
362        Self: Clone + Sized + Send + 'static,
363        T: Send + 'static,
364    {
365        self.clone().into_arc()
366    }
367
368    /// Creates a closure from a cloned supplier.
369    ///
370    /// The default implementation clones `self` and consumes the clone
371    /// to produce a closure. Concrete suppliers can override it to
372    /// avoid the additional clone.
373    fn to_fn(&self) -> impl FnMut() -> T
374    where
375        Self: Clone + Sized,
376    {
377        self.clone().into_fn()
378    }
379}
380
381// ==========================================================================
382// BoxSupplier - Single Ownership Implementation
383// ==========================================================================
384
385/// Box-based single ownership supplier.
386///
387/// Uses `Box<dyn FnMut() -> T>` for single ownership scenarios.
388/// This is the most lightweight supplier with zero reference
389/// counting overhead.
390///
391/// # Ownership Model
392///
393/// Methods consume `self` (move semantics). When you call a method
394/// like `map()`, the original supplier is consumed and you get a new
395/// one:
396///
397/// ```rust
398/// use prism3_function::{BoxSupplier, Supplier};
399///
400/// let supplier = BoxSupplier::new(|| 10);
401/// let mapped = supplier.map(|x| x * 2);
402/// // supplier is no longer usable here
403/// ```
404///
405/// # Examples
406///
407/// ## Counter
408///
409/// ```rust
410/// use prism3_function::{BoxSupplier, Supplier};
411///
412/// let mut counter = 0;
413/// let mut supplier = BoxSupplier::new(move || {
414///     counter += 1;
415///     counter
416/// });
417///
418/// assert_eq!(supplier.get(), 1);
419/// assert_eq!(supplier.get(), 2);
420/// ```
421///
422/// ## Method Chaining
423///
424/// ```rust
425/// use prism3_function::{BoxSupplier, Supplier};
426///
427/// let mut pipeline = BoxSupplier::new(|| 10)
428///     .map(|x| x * 2)
429///     .map(|x| x + 5);
430///
431/// assert_eq!(pipeline.get(), 25);
432/// ```
433///
434/// # Author
435///
436/// Haixing Hu
437pub struct BoxSupplier<T> {
438    function: Box<dyn FnMut() -> T>,
439}
440
441impl<T> BoxSupplier<T>
442where
443    T: 'static,
444{
445    /// Creates a new `BoxSupplier`.
446    ///
447    /// # Parameters
448    ///
449    /// * `f` - The closure to wrap
450    ///
451    /// # Returns
452    ///
453    /// A new `BoxSupplier<T>` instance
454    ///
455    /// # Examples
456    ///
457    /// ```rust
458    /// use prism3_function::{BoxSupplier, Supplier};
459    ///
460    /// let mut supplier = BoxSupplier::new(|| 42);
461    /// assert_eq!(supplier.get(), 42);
462    /// ```
463    pub fn new<F>(f: F) -> Self
464    where
465        F: FnMut() -> T + 'static,
466    {
467        BoxSupplier {
468            function: Box::new(f),
469        }
470    }
471
472    /// Creates a constant supplier.
473    ///
474    /// Returns a supplier that always produces the same value (via
475    /// cloning).
476    ///
477    /// # Parameters
478    ///
479    /// * `value` - The constant value to return
480    ///
481    /// # Returns
482    ///
483    /// A constant supplier
484    ///
485    /// # Examples
486    ///
487    /// ```rust
488    /// use prism3_function::{BoxSupplier, Supplier};
489    ///
490    /// let mut constant = BoxSupplier::constant(42);
491    /// assert_eq!(constant.get(), 42);
492    /// assert_eq!(constant.get(), 42);
493    /// ```
494    pub fn constant(value: T) -> Self
495    where
496        T: Clone + 'static,
497    {
498        BoxSupplier::new(move || value.clone())
499    }
500
501    /// Maps the output using a transformation function.
502    ///
503    /// Consumes self and returns a new supplier that applies the
504    /// mapper to each output.
505    ///
506    /// # Parameters
507    ///
508    /// * `mapper` - The mapper to apply to the output. Can be:
509    ///   - A closure: `|x: T| -> U`
510    ///   - A function pointer: `fn(T) -> U`
511    ///   - A `BoxMapper<T, U>`, `RcMapper<T, U>`, `ArcMapper<T, U>`
512    ///   - Any type implementing `Mapper<T, U>`
513    ///
514    /// # Returns
515    ///
516    /// A new mapped `BoxSupplier<U>`
517    ///
518    /// # Examples
519    ///
520    /// ## Using with closure
521    ///
522    /// ```rust
523    /// use prism3_function::{BoxSupplier, Supplier};
524    ///
525    /// let mut mapped = BoxSupplier::new(|| 10)
526    ///     .map(|x| x * 2)
527    ///     .map(|x| x + 5);
528    /// assert_eq!(mapped.get(), 25);
529    /// ```
530    ///
531    /// ## Using with Mapper object
532    ///
533    /// ```rust
534    /// use prism3_function::{BoxSupplier, BoxMapper, Supplier, Mapper};
535    ///
536    /// let mapper = BoxMapper::new(|x: i32| x * 2);
537    /// let mut supplier = BoxSupplier::new(|| 10)
538    ///     .map(mapper);
539    /// assert_eq!(supplier.get(), 20);
540    /// ```
541    pub fn map<U, F>(mut self, mut mapper: F) -> BoxSupplier<U>
542    where
543        F: Mapper<T, U> + 'static,
544        U: 'static,
545    {
546        BoxSupplier::new(move || mapper.apply(self.get()))
547    }
548
549    /// Filters output based on a predicate.
550    ///
551    /// Returns a new supplier that returns `Some(value)` if the
552    /// predicate is satisfied, `None` otherwise.
553    ///
554    /// # Parameters
555    ///
556    /// * `predicate` - The predicate to test the supplied value
557    ///
558    /// # Returns
559    ///
560    /// A new filtered `BoxSupplier<Option<T>>`
561    ///
562    /// # Examples
563    ///
564    /// ```rust
565    /// use prism3_function::{BoxSupplier, Supplier};
566    ///
567    /// let mut counter = 0;
568    /// let mut filtered = BoxSupplier::new(move || {
569    ///     counter += 1;
570    ///     counter
571    /// }).filter(|x| x % 2 == 0);
572    ///
573    /// assert_eq!(filtered.get(), None);     // 1 is odd
574    /// assert_eq!(filtered.get(), Some(2));  // 2 is even
575    /// ```
576    pub fn filter<P>(mut self, mut predicate: P) -> BoxSupplier<Option<T>>
577    where
578        P: FnMut(&T) -> bool + 'static,
579    {
580        BoxSupplier::new(move || {
581            let value = self.get();
582            if predicate(&value) {
583                Some(value)
584            } else {
585                None
586            }
587        })
588    }
589
590    /// Combines this supplier with another, producing a tuple.
591    ///
592    /// Consumes both suppliers and returns a new supplier that
593    /// produces `(T, U)` tuples.
594    ///
595    /// # Parameters
596    ///
597    /// * `other` - The other supplier to combine with
598    ///
599    /// # Returns
600    ///
601    /// A new `BoxSupplier<(T, U)>`
602    ///
603    /// # Examples
604    ///
605    /// ```rust
606    /// use prism3_function::{BoxSupplier, Supplier};
607    ///
608    /// let first = BoxSupplier::new(|| 42);
609    /// let second = BoxSupplier::new(|| "hello");
610    /// let mut zipped = first.zip(second);
611    ///
612    /// assert_eq!(zipped.get(), (42, "hello"));
613    /// ```
614    pub fn zip<U>(mut self, mut other: BoxSupplier<U>) -> BoxSupplier<(T, U)>
615    where
616        U: 'static,
617    {
618        BoxSupplier::new(move || (self.get(), other.get()))
619    }
620
621    /// Creates a memoizing supplier.
622    ///
623    /// Returns a new supplier that caches the first value it
624    /// produces. All subsequent calls return the cached value.
625    ///
626    /// # Returns
627    ///
628    /// A new memoized `BoxSupplier<T>`
629    ///
630    /// # Examples
631    ///
632    /// ```rust
633    /// use prism3_function::{BoxSupplier, Supplier};
634    ///
635    /// let mut call_count = 0;
636    /// let mut memoized = BoxSupplier::new(move || {
637    ///     call_count += 1;
638    ///     42
639    /// }).memoize();
640    ///
641    /// assert_eq!(memoized.get(), 42); // Calls underlying function
642    /// assert_eq!(memoized.get(), 42); // Returns cached value
643    /// ```
644    pub fn memoize(mut self) -> BoxSupplier<T>
645    where
646        T: Clone + 'static,
647    {
648        let mut cache: Option<T> = None;
649        BoxSupplier::new(move || {
650            if let Some(ref cached) = cache {
651                cached.clone()
652            } else {
653                let value = self.get();
654                cache = Some(value.clone());
655                value
656            }
657        })
658    }
659}
660
661impl<T> Supplier<T> for BoxSupplier<T> {
662    fn get(&mut self) -> T {
663        (self.function)()
664    }
665
666    fn into_box(self) -> BoxSupplier<T>
667    where
668        T: 'static,
669    {
670        self
671    }
672
673    fn into_rc(self) -> RcSupplier<T>
674    where
675        T: 'static,
676    {
677        RcSupplier::new(self.function)
678    }
679
680    // into_arc cannot be implemented because the inner function may not be Send.
681    // Attempting to call this method will result in a compiler error due to missing Send bound.
682    // Use ArcSupplier::new directly with a Send closure instead.
683    // compile_error!("Cannot convert BoxSupplier to ArcSupplier: inner function may not implement Send");
684
685    fn into_fn(self) -> impl FnMut() -> T {
686        self.function
687    }
688
689    // NOTE: `BoxSupplier` is not `Clone`, so it cannot offer optimized
690    // `to_box`, `to_rc`, `to_arc`, or `to_fn` implementations. Invoking
691    // the default trait methods will not compile because the required
692    // `Clone` bound is not satisfied.
693}
694
695// ==========================================================================
696// ArcSupplier - Thread-safe Shared Ownership Implementation
697// ==========================================================================
698
699/// Thread-safe shared ownership supplier.
700///
701/// Uses `Arc<Mutex<dyn FnMut() -> T + Send>>` for thread-safe
702/// shared ownership. Can be cloned and sent across threads.
703///
704/// # Ownership Model
705///
706/// Methods borrow `&self` instead of consuming `self`. The original
707/// supplier remains usable after method calls:
708///
709/// ```rust
710/// use prism3_function::{ArcSupplier, Supplier};
711///
712/// let source = ArcSupplier::new(|| 10);
713/// let mapped = source.map(|x| x * 2);
714/// // source is still usable here!
715/// ```
716///
717/// # Examples
718///
719/// ## Thread-safe Counter
720///
721/// ```rust
722/// use prism3_function::{ArcSupplier, Supplier};
723/// use std::sync::{Arc, Mutex};
724/// use std::thread;
725///
726/// let counter = Arc::new(Mutex::new(0));
727/// let counter_clone = Arc::clone(&counter);
728///
729/// let supplier = ArcSupplier::new(move || {
730///     let mut c = counter_clone.lock().unwrap();
731///     *c += 1;
732///     *c
733/// });
734///
735/// let mut s1 = supplier.clone();
736/// let mut s2 = supplier.clone();
737///
738/// let h1 = thread::spawn(move || s1.get());
739/// let h2 = thread::spawn(move || s2.get());
740///
741/// let v1 = h1.join().unwrap();
742/// let v2 = h2.join().unwrap();
743/// assert!(v1 != v2);
744/// ```
745///
746/// ## Reusable Transformations
747///
748/// ```rust
749/// use prism3_function::{ArcSupplier, Supplier};
750///
751/// let base = ArcSupplier::new(|| 10);
752/// let doubled = base.map(|x| x * 2);
753/// let tripled = base.map(|x| x * 3);
754///
755/// // All remain usable
756/// let mut b = base;
757/// let mut d = doubled;
758/// let mut t = tripled;
759/// assert_eq!(b.get(), 10);
760/// assert_eq!(d.get(), 20);
761/// assert_eq!(t.get(), 30);
762/// ```
763///
764/// # Author
765///
766/// Haixing Hu
767pub struct ArcSupplier<T> {
768    function: Arc<Mutex<dyn FnMut() -> T + Send>>,
769}
770
771impl<T> ArcSupplier<T>
772where
773    T: Send + 'static,
774{
775    /// Creates a new `ArcSupplier`.
776    ///
777    /// # Parameters
778    ///
779    /// * `f` - The closure to wrap
780    ///
781    /// # Returns
782    ///
783    /// A new `ArcSupplier<T>` instance
784    ///
785    /// # Examples
786    ///
787    /// ```rust
788    /// use prism3_function::{ArcSupplier, Supplier};
789    ///
790    /// let supplier = ArcSupplier::new(|| 42);
791    /// let mut s = supplier;
792    /// assert_eq!(s.get(), 42);
793    /// ```
794    pub fn new<F>(f: F) -> Self
795    where
796        F: FnMut() -> T + Send + 'static,
797    {
798        ArcSupplier {
799            function: Arc::new(Mutex::new(f)),
800        }
801    }
802
803    /// Creates a constant supplier.
804    ///
805    /// # Parameters
806    ///
807    /// * `value` - The constant value to return
808    ///
809    /// # Returns
810    ///
811    /// A constant supplier
812    ///
813    /// # Examples
814    ///
815    /// ```rust
816    /// use prism3_function::{ArcSupplier, Supplier};
817    ///
818    /// let constant = ArcSupplier::constant(42);
819    /// let mut s = constant;
820    /// assert_eq!(s.get(), 42);
821    /// assert_eq!(s.get(), 42);
822    /// ```
823    pub fn constant(value: T) -> Self
824    where
825        T: Clone + 'static,
826    {
827        ArcSupplier::new(move || value.clone())
828    }
829
830    /// Maps the output using a transformation function.
831    ///
832    /// Borrows `&self`, doesn't consume the original supplier.
833    ///
834    /// # Parameters
835    ///
836    /// * `mapper` - The mapper to apply to the output. Can be:
837    ///   - A closure: `|x: T| -> U` (must be `Send`)
838    ///   - A function pointer: `fn(T) -> U`
839    ///   - A `BoxMapper<T, U>`, `RcMapper<T, U>`, `ArcMapper<T, U>`
840    ///   - Any type implementing `Mapper<T, U> + Send`
841    ///
842    /// # Returns
843    ///
844    /// A new mapped `ArcSupplier<U>`
845    ///
846    /// # Examples
847    ///
848    /// ## Using with closure
849    ///
850    /// ```rust
851    /// use prism3_function::{ArcSupplier, Supplier};
852    ///
853    /// let source = ArcSupplier::new(|| 10);
854    /// let mapped = source.map(|x| x * 2);
855    /// // source is still usable
856    /// let mut s = mapped;
857    /// assert_eq!(s.get(), 20);
858    /// ```
859    ///
860    /// ## Using with Mapper object
861    ///
862    /// ```rust
863    /// use prism3_function::{ArcSupplier, ArcMapper, Supplier, Mapper};
864    ///
865    /// let mapper = ArcMapper::new(|x: i32| x * 2);
866    /// let source = ArcSupplier::new(|| 10);
867    /// let mut supplier = source.map(mapper);
868    /// assert_eq!(supplier.get(), 20);
869    /// ```
870    pub fn map<U, F>(&self, mapper: F) -> ArcSupplier<U>
871    where
872        F: Mapper<T, U> + Send + 'static,
873        U: Send + 'static,
874    {
875        let self_fn = Arc::clone(&self.function);
876        let mapper = Arc::new(Mutex::new(mapper));
877        ArcSupplier {
878            function: Arc::new(Mutex::new(move || {
879                let value = self_fn.lock().unwrap()();
880                mapper.lock().unwrap().apply(value)
881            })),
882        }
883    }
884
885    /// Filters output based on a predicate.
886    ///
887    /// # Parameters
888    ///
889    /// * `predicate` - The predicate to test the supplied value
890    ///
891    /// # Returns
892    ///
893    /// A new filtered `ArcSupplier<Option<T>>`
894    ///
895    /// # Examples
896    ///
897    /// ```rust
898    /// use prism3_function::{ArcSupplier, Supplier};
899    /// use std::sync::{Arc, Mutex};
900    ///
901    /// let counter = Arc::new(Mutex::new(0));
902    /// let counter_clone = Arc::clone(&counter);
903    /// let source = ArcSupplier::new(move || {
904    ///     let mut c = counter_clone.lock().unwrap();
905    ///     *c += 1;
906    ///     *c
907    /// });
908    /// let filtered = source.filter(|x| x % 2 == 0);
909    ///
910    /// let mut s = filtered;
911    /// assert_eq!(s.get(), None);     // 1 is odd
912    /// assert_eq!(s.get(), Some(2));  // 2 is even
913    /// ```
914    pub fn filter<P>(&self, predicate: P) -> ArcSupplier<Option<T>>
915    where
916        P: FnMut(&T) -> bool + Send + 'static,
917    {
918        let self_fn = Arc::clone(&self.function);
919        let predicate = Arc::new(Mutex::new(predicate));
920        ArcSupplier {
921            function: Arc::new(Mutex::new(move || {
922                let value = self_fn.lock().unwrap()();
923                if predicate.lock().unwrap()(&value) {
924                    Some(value)
925                } else {
926                    None
927                }
928            })),
929        }
930    }
931
932    /// Combines this supplier with another, producing a tuple.
933    ///
934    /// # Parameters
935    ///
936    /// * `other` - The other supplier to combine with. **Note: This parameter
937    ///   is passed by reference, so the original supplier remains usable.**
938    ///   Can be:
939    ///   - An `ArcSupplier<U>` (passed by reference)
940    ///   - Any type implementing `Supplier<U> + Send`
941    ///
942    /// # Returns
943    ///
944    /// A new `ArcSupplier<(T, U)>`
945    ///
946    /// # Examples
947    ///
948    /// ```rust
949    /// use prism3_function::{ArcSupplier, Supplier};
950    ///
951    /// let first = ArcSupplier::new(|| 42);
952    /// let second = ArcSupplier::new(|| "hello");
953    ///
954    /// // second is passed by reference, so it remains usable
955    /// let zipped = first.zip(&second);
956    ///
957    /// let mut z = zipped;
958    /// assert_eq!(z.get(), (42, "hello"));
959    ///
960    /// // Both first and second still usable
961    /// let mut f = first;
962    /// let mut s = second;
963    /// assert_eq!(f.get(), 42);
964    /// assert_eq!(s.get(), "hello");
965    /// ```
966    pub fn zip<U>(&self, other: &ArcSupplier<U>) -> ArcSupplier<(T, U)>
967    where
968        U: Send + 'static,
969    {
970        let first = Arc::clone(&self.function);
971        let second = Arc::clone(&other.function);
972        ArcSupplier {
973            function: Arc::new(Mutex::new(move || {
974                (first.lock().unwrap()(), second.lock().unwrap()())
975            })),
976        }
977    }
978
979    /// Creates a memoizing supplier.
980    ///
981    /// # Returns
982    ///
983    /// A new memoized `ArcSupplier<T>`
984    ///
985    /// # Examples
986    ///
987    /// ```rust
988    /// use prism3_function::{ArcSupplier, Supplier};
989    /// use std::sync::{Arc, Mutex};
990    ///
991    /// let call_count = Arc::new(Mutex::new(0));
992    /// let call_count_clone = Arc::clone(&call_count);
993    /// let source = ArcSupplier::new(move || {
994    ///     let mut c = call_count_clone.lock().unwrap();
995    ///     *c += 1;
996    ///     42
997    /// });
998    /// let memoized = source.memoize();
999    ///
1000    /// let mut s = memoized;
1001    /// assert_eq!(s.get(), 42); // Calls underlying function
1002    /// assert_eq!(s.get(), 42); // Returns cached value
1003    /// assert_eq!(*call_count.lock().unwrap(), 1);
1004    /// ```
1005    pub fn memoize(&self) -> ArcSupplier<T>
1006    where
1007        T: Clone + 'static,
1008    {
1009        let self_fn = Arc::clone(&self.function);
1010        let cache: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
1011        ArcSupplier {
1012            function: Arc::new(Mutex::new(move || {
1013                let mut cache_guard = cache.lock().unwrap();
1014                if let Some(ref cached) = *cache_guard {
1015                    cached.clone()
1016                } else {
1017                    let value = self_fn.lock().unwrap()();
1018                    *cache_guard = Some(value.clone());
1019                    value
1020                }
1021            })),
1022        }
1023    }
1024}
1025
1026impl<T> Supplier<T> for ArcSupplier<T> {
1027    fn get(&mut self) -> T {
1028        (self.function.lock().unwrap())()
1029    }
1030
1031    fn into_box(self) -> BoxSupplier<T>
1032    where
1033        T: 'static,
1034    {
1035        let self_fn = self.function;
1036        BoxSupplier::new(move || self_fn.lock().unwrap()())
1037    }
1038
1039    fn into_rc(self) -> RcSupplier<T>
1040    where
1041        T: 'static,
1042    {
1043        let self_fn = self.function;
1044        RcSupplier::new(move || self_fn.lock().unwrap()())
1045    }
1046
1047    fn into_arc(self) -> ArcSupplier<T>
1048    where
1049        T: Send + 'static,
1050    {
1051        self
1052    }
1053
1054    fn into_fn(self) -> impl FnMut() -> T {
1055        let function = self.function;
1056        move || function.lock().unwrap()()
1057    }
1058
1059    fn to_box(&self) -> BoxSupplier<T>
1060    where
1061        Self: Clone + Sized + 'static,
1062        T: 'static,
1063    {
1064        let function = Arc::clone(&self.function);
1065        BoxSupplier::new(move || function.lock().unwrap()())
1066    }
1067
1068    fn to_rc(&self) -> RcSupplier<T>
1069    where
1070        Self: Clone + Sized + 'static,
1071        T: 'static,
1072    {
1073        let function = Arc::clone(&self.function);
1074        RcSupplier::new(move || function.lock().unwrap()())
1075    }
1076
1077    fn to_arc(&self) -> ArcSupplier<T>
1078    where
1079        Self: Clone + Sized + Send + 'static,
1080        T: Send + 'static,
1081    {
1082        self.clone()
1083    }
1084
1085    fn to_fn(&self) -> impl FnMut() -> T
1086    where
1087        Self: Clone + Sized,
1088    {
1089        let function = Arc::clone(&self.function);
1090        move || function.lock().unwrap()()
1091    }
1092}
1093
1094impl<T> Clone for ArcSupplier<T> {
1095    /// Clones the `ArcSupplier`.
1096    ///
1097    /// Creates a new instance that shares the underlying function
1098    /// with the original.
1099    fn clone(&self) -> Self {
1100        Self {
1101            function: Arc::clone(&self.function),
1102        }
1103    }
1104}
1105
1106// ==========================================================================
1107// RcSupplier - Single-threaded Shared Ownership Implementation
1108// ==========================================================================
1109
1110/// Single-threaded shared ownership supplier.
1111///
1112/// Uses `Rc<RefCell<dyn FnMut() -> T>>` for single-threaded shared
1113/// ownership. Can be cloned but not sent across threads.
1114///
1115/// # Ownership Model
1116///
1117/// Like `ArcSupplier`, methods borrow `&self` instead of consuming
1118/// `self`:
1119///
1120/// ```rust
1121/// use prism3_function::{RcSupplier, Supplier};
1122///
1123/// let source = RcSupplier::new(|| 10);
1124/// let mapped = source.map(|x| x * 2);
1125/// // source is still usable here!
1126/// ```
1127///
1128/// # Examples
1129///
1130/// ## Shared Counter
1131///
1132/// ```rust
1133/// use prism3_function::{RcSupplier, Supplier};
1134/// use std::rc::Rc;
1135/// use std::cell::RefCell;
1136///
1137/// let counter = Rc::new(RefCell::new(0));
1138/// let counter_clone = Rc::clone(&counter);
1139///
1140/// let supplier = RcSupplier::new(move || {
1141///     let mut c = counter_clone.borrow_mut();
1142///     *c += 1;
1143///     *c
1144/// });
1145///
1146/// let mut s1 = supplier.clone();
1147/// let mut s2 = supplier.clone();
1148/// assert_eq!(s1.get(), 1);
1149/// assert_eq!(s2.get(), 2);
1150/// ```
1151///
1152/// ## Reusable Transformations
1153///
1154/// ```rust
1155/// use prism3_function::{RcSupplier, Supplier};
1156///
1157/// let base = RcSupplier::new(|| 10);
1158/// let doubled = base.map(|x| x * 2);
1159/// let tripled = base.map(|x| x * 3);
1160///
1161/// let mut b = base;
1162/// let mut d = doubled;
1163/// let mut t = tripled;
1164/// assert_eq!(b.get(), 10);
1165/// assert_eq!(d.get(), 20);
1166/// assert_eq!(t.get(), 30);
1167/// ```
1168///
1169/// # Author
1170///
1171/// Haixing Hu
1172pub struct RcSupplier<T> {
1173    function: Rc<RefCell<dyn FnMut() -> T>>,
1174}
1175
1176impl<T> RcSupplier<T>
1177where
1178    T: 'static,
1179{
1180    /// Creates a new `RcSupplier`.
1181    ///
1182    /// # Parameters
1183    ///
1184    /// * `f` - The closure to wrap
1185    ///
1186    /// # Returns
1187    ///
1188    /// A new `RcSupplier<T>` instance
1189    ///
1190    /// # Examples
1191    ///
1192    /// ```rust
1193    /// use prism3_function::{RcSupplier, Supplier};
1194    ///
1195    /// let supplier = RcSupplier::new(|| 42);
1196    /// let mut s = supplier;
1197    /// assert_eq!(s.get(), 42);
1198    /// ```
1199    pub fn new<F>(f: F) -> Self
1200    where
1201        F: FnMut() -> T + 'static,
1202    {
1203        RcSupplier {
1204            function: Rc::new(RefCell::new(f)),
1205        }
1206    }
1207
1208    /// Creates a constant supplier.
1209    ///
1210    /// # Parameters
1211    ///
1212    /// * `value` - The constant value to return
1213    ///
1214    /// # Returns
1215    ///
1216    /// A constant supplier
1217    ///
1218    /// # Examples
1219    ///
1220    /// ```rust
1221    /// use prism3_function::{RcSupplier, Supplier};
1222    ///
1223    /// let constant = RcSupplier::constant(42);
1224    /// let mut s = constant;
1225    /// assert_eq!(s.get(), 42);
1226    /// assert_eq!(s.get(), 42);
1227    /// ```
1228    pub fn constant(value: T) -> Self
1229    where
1230        T: Clone + 'static,
1231    {
1232        RcSupplier::new(move || value.clone())
1233    }
1234
1235    /// Maps the output using a transformation function.
1236    ///
1237    /// Borrows `&self`, doesn't consume the original supplier.
1238    ///
1239    /// # Parameters
1240    ///
1241    /// * `mapper` - The mapper to apply to the output. Can be:
1242    ///   - A closure: `|x: T| -> U`
1243    ///   - A function pointer: `fn(T) -> U`
1244    ///   - A `BoxMapper<T, U>`, `RcMapper<T, U>`, `ArcMapper<T, U>`
1245    ///   - Any type implementing `Mapper<T, U>`
1246    ///
1247    /// # Returns
1248    ///
1249    /// A new mapped `RcSupplier<U>`
1250    ///
1251    /// # Examples
1252    ///
1253    /// ## Using with closure
1254    ///
1255    /// ```rust
1256    /// use prism3_function::{RcSupplier, Supplier};
1257    ///
1258    /// let source = RcSupplier::new(|| 10);
1259    /// let mapped = source.map(|x| x * 2);
1260    /// // source is still usable
1261    /// let mut s = mapped;
1262    /// assert_eq!(s.get(), 20);
1263    /// ```
1264    ///
1265    /// ## Using with Mapper object
1266    ///
1267    /// ```rust
1268    /// use prism3_function::{RcSupplier, RcMapper, Supplier, Mapper};
1269    ///
1270    /// let mapper = RcMapper::new(|x: i32| x * 2);
1271    /// let source = RcSupplier::new(|| 10);
1272    /// let mut supplier = source.map(mapper);
1273    /// assert_eq!(supplier.get(), 20);
1274    /// ```
1275    pub fn map<U, F>(&self, mapper: F) -> RcSupplier<U>
1276    where
1277        F: Mapper<T, U> + 'static,
1278        U: 'static,
1279    {
1280        let self_fn = Rc::clone(&self.function);
1281        let mapper = Rc::new(RefCell::new(mapper));
1282        RcSupplier {
1283            function: Rc::new(RefCell::new(move || {
1284                let value = self_fn.borrow_mut()();
1285                mapper.borrow_mut().apply(value)
1286            })),
1287        }
1288    }
1289
1290    /// Filters output based on a predicate.
1291    ///
1292    /// # Parameters
1293    ///
1294    /// * `predicate` - The predicate to test the supplied value
1295    ///
1296    /// # Returns
1297    ///
1298    /// A new filtered `RcSupplier<Option<T>>`
1299    ///
1300    /// # Examples
1301    ///
1302    /// ```rust
1303    /// use prism3_function::{RcSupplier, Supplier};
1304    /// use std::rc::Rc;
1305    /// use std::cell::RefCell;
1306    ///
1307    /// let counter = Rc::new(RefCell::new(0));
1308    /// let counter_clone = Rc::clone(&counter);
1309    /// let source = RcSupplier::new(move || {
1310    ///     let mut c = counter_clone.borrow_mut();
1311    ///     *c += 1;
1312    ///     *c
1313    /// });
1314    /// let filtered = source.filter(|x| x % 2 == 0);
1315    ///
1316    /// let mut s = filtered;
1317    /// assert_eq!(s.get(), None);     // 1 is odd
1318    /// assert_eq!(s.get(), Some(2));  // 2 is even
1319    /// ```
1320    pub fn filter<P>(&self, predicate: P) -> RcSupplier<Option<T>>
1321    where
1322        P: FnMut(&T) -> bool + 'static,
1323    {
1324        let self_fn = Rc::clone(&self.function);
1325        let predicate = Rc::new(RefCell::new(predicate));
1326        RcSupplier {
1327            function: Rc::new(RefCell::new(move || {
1328                let value = self_fn.borrow_mut()();
1329                if predicate.borrow_mut()(&value) {
1330                    Some(value)
1331                } else {
1332                    None
1333                }
1334            })),
1335        }
1336    }
1337
1338    /// Combines this supplier with another, producing a tuple.
1339    ///
1340    /// # Parameters
1341    ///
1342    /// * `other` - The other supplier to combine with. **Note: This parameter
1343    ///   is passed by reference, so the original supplier remains usable.**
1344    ///   Can be:
1345    ///   - An `RcSupplier<U>` (passed by reference)
1346    ///   - Any type implementing `Supplier<U>`
1347    ///
1348    /// # Returns
1349    ///
1350    /// A new `RcSupplier<(T, U)>`
1351    ///
1352    /// # Examples
1353    ///
1354    /// ```rust
1355    /// use prism3_function::{RcSupplier, Supplier};
1356    ///
1357    /// let first = RcSupplier::new(|| 42);
1358    /// let second = RcSupplier::new(|| "hello");
1359    ///
1360    /// // second is passed by reference, so it remains usable
1361    /// let zipped = first.zip(&second);
1362    ///
1363    /// let mut z = zipped;
1364    /// assert_eq!(z.get(), (42, "hello"));
1365    ///
1366    /// // Both first and second still usable
1367    /// let mut f = first;
1368    /// let mut s = second;
1369    /// assert_eq!(f.get(), 42);
1370    /// assert_eq!(s.get(), "hello");
1371    /// ```
1372    pub fn zip<U>(&self, other: &RcSupplier<U>) -> RcSupplier<(T, U)>
1373    where
1374        U: 'static,
1375    {
1376        let first = Rc::clone(&self.function);
1377        let second = Rc::clone(&other.function);
1378        RcSupplier {
1379            function: Rc::new(RefCell::new(move || {
1380                (first.borrow_mut()(), second.borrow_mut()())
1381            })),
1382        }
1383    }
1384
1385    /// Creates a memoizing supplier.
1386    ///
1387    /// # Returns
1388    ///
1389    /// A new memoized `RcSupplier<T>`
1390    ///
1391    /// # Examples
1392    ///
1393    /// ```rust
1394    /// use prism3_function::{RcSupplier, Supplier};
1395    /// use std::rc::Rc;
1396    /// use std::cell::RefCell;
1397    ///
1398    /// let call_count = Rc::new(RefCell::new(0));
1399    /// let call_count_clone = Rc::clone(&call_count);
1400    /// let source = RcSupplier::new(move || {
1401    ///     let mut c = call_count_clone.borrow_mut();
1402    ///     *c += 1;
1403    ///     42
1404    /// });
1405    /// let memoized = source.memoize();
1406    ///
1407    /// let mut s = memoized;
1408    /// assert_eq!(s.get(), 42); // Calls underlying function
1409    /// assert_eq!(s.get(), 42); // Returns cached value
1410    /// assert_eq!(*call_count.borrow(), 1);
1411    /// ```
1412    pub fn memoize(&self) -> RcSupplier<T>
1413    where
1414        T: Clone + 'static,
1415    {
1416        let self_fn = Rc::clone(&self.function);
1417        let cache: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
1418        RcSupplier {
1419            function: Rc::new(RefCell::new(move || {
1420                let mut cache_ref = cache.borrow_mut();
1421                if let Some(ref cached) = *cache_ref {
1422                    cached.clone()
1423                } else {
1424                    let value = self_fn.borrow_mut()();
1425                    *cache_ref = Some(value.clone());
1426                    value
1427                }
1428            })),
1429        }
1430    }
1431}
1432
1433impl<T> Supplier<T> for RcSupplier<T> {
1434    fn get(&mut self) -> T {
1435        (self.function.borrow_mut())()
1436    }
1437
1438    fn into_box(self) -> BoxSupplier<T>
1439    where
1440        T: 'static,
1441    {
1442        let self_fn = self.function;
1443        BoxSupplier::new(move || self_fn.borrow_mut()())
1444    }
1445
1446    fn into_rc(self) -> RcSupplier<T>
1447    where
1448        T: 'static,
1449    {
1450        self
1451    }
1452
1453    // into_arc cannot be implemented because RcSupplier does not implement Send.
1454    // Attempting to call this method will result in a compiler error due to missing Send bound.
1455    // Use ArcSupplier::new directly instead.
1456    // compile_error!("Cannot convert RcSupplier to ArcSupplier: RcSupplier does not implement Send");
1457
1458    fn into_fn(self) -> impl FnMut() -> T {
1459        let function = self.function;
1460        move || function.borrow_mut()()
1461    }
1462
1463    fn to_box(&self) -> BoxSupplier<T>
1464    where
1465        Self: Clone + Sized + 'static,
1466        T: 'static,
1467    {
1468        let function = Rc::clone(&self.function);
1469        BoxSupplier::new(move || function.borrow_mut()())
1470    }
1471
1472    fn to_rc(&self) -> RcSupplier<T>
1473    where
1474        Self: Clone + Sized + 'static,
1475        T: 'static,
1476    {
1477        self.clone()
1478    }
1479
1480    // NOTE: `RcSupplier` cannot be converted to `ArcSupplier` because it
1481    // is not `Send`. Calling the default `to_arc` would fail compilation
1482    // due to the missing `Send` bound.
1483
1484    fn to_fn(&self) -> impl FnMut() -> T
1485    where
1486        Self: Clone + Sized,
1487    {
1488        let function = Rc::clone(&self.function);
1489        move || function.borrow_mut()()
1490    }
1491}
1492
1493impl<T> Clone for RcSupplier<T> {
1494    /// Clones the `RcSupplier`.
1495    ///
1496    /// Creates a new instance that shares the underlying function
1497    /// with the original.
1498    fn clone(&self) -> Self {
1499        Self {
1500            function: Rc::clone(&self.function),
1501        }
1502    }
1503}
1504
1505// ==========================================================================
1506// Implement Supplier for Closures
1507// ==========================================================================
1508
1509impl<T, F> Supplier<T> for F
1510where
1511    F: FnMut() -> T,
1512{
1513    fn get(&mut self) -> T {
1514        self()
1515    }
1516
1517    fn into_box(self) -> BoxSupplier<T>
1518    where
1519        Self: Sized + 'static,
1520        T: 'static,
1521    {
1522        BoxSupplier::new(self)
1523    }
1524
1525    fn into_rc(self) -> RcSupplier<T>
1526    where
1527        Self: Sized + 'static,
1528        T: 'static,
1529    {
1530        RcSupplier::new(self)
1531    }
1532
1533    fn into_arc(self) -> ArcSupplier<T>
1534    where
1535        Self: Sized + Send + 'static,
1536        T: Send + 'static,
1537    {
1538        ArcSupplier::new(self)
1539    }
1540
1541    fn into_fn(self) -> impl FnMut() -> T
1542    where
1543        Self: Sized,
1544    {
1545        self
1546    }
1547
1548    fn to_box(&self) -> BoxSupplier<T>
1549    where
1550        Self: Clone + Sized + 'static,
1551        T: 'static,
1552    {
1553        self.clone().into_box()
1554    }
1555
1556    fn to_rc(&self) -> RcSupplier<T>
1557    where
1558        Self: Clone + Sized + 'static,
1559        T: 'static,
1560    {
1561        self.clone().into_rc()
1562    }
1563
1564    fn to_arc(&self) -> ArcSupplier<T>
1565    where
1566        Self: Clone + Sized + Send + 'static,
1567        T: Send + 'static,
1568    {
1569        self.clone().into_arc()
1570    }
1571
1572    fn to_fn(&self) -> impl FnMut() -> T
1573    where
1574        Self: Clone + Sized,
1575    {
1576        self.clone()
1577    }
1578}
1579
1580// ==========================================================================
1581// Extension Trait for Closure Operations
1582// ==========================================================================
1583
1584/// Extension trait providing supplier operations for closures
1585///
1586/// Provides composition methods (`map`, `filter`, `zip`, `memoize`) for
1587/// closures implementing `FnMut() -> T` without requiring explicit
1588/// wrapping in `BoxSupplier`.
1589///
1590/// This trait is automatically implemented for all closures and function
1591/// pointers that implement `FnMut() -> T`.
1592///
1593/// # Design Rationale
1594///
1595/// While closures automatically implement `Supplier<T>` through blanket
1596/// implementation, they don't have access to instance methods like
1597/// `map`, `filter`, and `zip`. This extension trait provides those
1598/// methods, returning `BoxSupplier` for maximum flexibility.
1599///
1600/// # Examples
1601///
1602/// ## Map transformation
1603///
1604/// ```rust
1605/// use prism3_function::{Supplier, FnSupplierOps};
1606///
1607/// let mut counter = 0;
1608/// let mut mapped = (move || {
1609///     counter += 1;
1610///     counter
1611/// }).map(|x| x * 2);
1612///
1613/// assert_eq!(mapped.get(), 2);
1614/// assert_eq!(mapped.get(), 4);
1615/// ```
1616///
1617/// ## Filter values
1618///
1619/// ```rust
1620/// use prism3_function::{Supplier, FnSupplierOps};
1621///
1622/// let mut counter = 0;
1623/// let mut filtered = (move || {
1624///     counter += 1;
1625///     counter
1626/// }).filter(|x| x % 2 == 0);
1627///
1628/// assert_eq!(filtered.get(), None);     // 1 is odd
1629/// assert_eq!(filtered.get(), Some(2));  // 2 is even
1630/// ```
1631///
1632/// ## Combine with zip
1633///
1634/// ```rust
1635/// use prism3_function::{Supplier, FnSupplierOps, BoxSupplier};
1636///
1637/// let first = || 42;
1638/// let second = BoxSupplier::new(|| "hello");
1639/// let mut zipped = first.zip(second);
1640///
1641/// assert_eq!(zipped.get(), (42, "hello"));
1642/// ```
1643///
1644/// # Author
1645///
1646/// Haixing Hu
1647pub trait FnSupplierOps<T>: FnMut() -> T + Sized + 'static {
1648    /// Maps the output using a transformation function.
1649    ///
1650    /// Consumes the closure and returns a new supplier that applies
1651    /// the mapper to each output.
1652    ///
1653    /// # Parameters
1654    ///
1655    /// * `mapper` - The mapper to apply to the output
1656    ///
1657    /// # Returns
1658    ///
1659    /// A new mapped `BoxSupplier<U>`
1660    ///
1661    /// # Examples
1662    ///
1663    /// ```rust
1664    /// use prism3_function::{Supplier, FnSupplierOps};
1665    ///
1666    /// let mut mapped = (|| 10)
1667    ///     .map(|x| x * 2)
1668    ///     .map(|x| x + 5);
1669    /// assert_eq!(mapped.get(), 25);
1670    /// ```
1671    fn map<U, M>(self, mapper: M) -> BoxSupplier<U>
1672    where
1673        M: Mapper<T, U> + 'static,
1674        U: 'static,
1675        T: 'static,
1676    {
1677        BoxSupplier::new(self).map(mapper)
1678    }
1679
1680    /// Filters output based on a predicate.
1681    ///
1682    /// Returns a new supplier that returns `Some(value)` if the
1683    /// predicate is satisfied, `None` otherwise.
1684    ///
1685    /// # Parameters
1686    ///
1687    /// * `predicate` - The predicate to test the supplied value
1688    ///
1689    /// # Returns
1690    ///
1691    /// A new filtered `BoxSupplier<Option<T>>`
1692    ///
1693    /// # Examples
1694    ///
1695    /// ```rust
1696    /// use prism3_function::{Supplier, FnSupplierOps};
1697    ///
1698    /// let mut counter = 0;
1699    /// let mut filtered = (move || {
1700    ///     counter += 1;
1701    ///     counter
1702    /// }).filter(|x| x % 2 == 0);
1703    ///
1704    /// assert_eq!(filtered.get(), None);     // 1 is odd
1705    /// assert_eq!(filtered.get(), Some(2));  // 2 is even
1706    /// ```
1707    fn filter<P>(self, predicate: P) -> BoxSupplier<Option<T>>
1708    where
1709        P: FnMut(&T) -> bool + 'static,
1710        T: 'static,
1711    {
1712        BoxSupplier::new(self).filter(predicate)
1713    }
1714
1715    /// Combines this supplier with another, producing a tuple.
1716    ///
1717    /// Consumes both suppliers and returns a new supplier that
1718    /// produces `(T, U)` tuples.
1719    ///
1720    /// # Parameters
1721    ///
1722    /// * `other` - The other supplier to combine with
1723    ///
1724    /// # Returns
1725    ///
1726    /// A new `BoxSupplier<(T, U)>`
1727    ///
1728    /// # Examples
1729    ///
1730    /// ```rust
1731    /// use prism3_function::{Supplier, FnSupplierOps, BoxSupplier};
1732    ///
1733    /// let first = || 42;
1734    /// let second = BoxSupplier::new(|| "hello");
1735    /// let mut zipped = first.zip(second);
1736    ///
1737    /// assert_eq!(zipped.get(), (42, "hello"));
1738    /// ```
1739    fn zip<U>(self, other: BoxSupplier<U>) -> BoxSupplier<(T, U)>
1740    where
1741        U: 'static,
1742        T: 'static,
1743    {
1744        BoxSupplier::new(self).zip(other)
1745    }
1746
1747    /// Creates a memoizing supplier.
1748    ///
1749    /// Returns a new supplier that caches the first value it
1750    /// produces. All subsequent calls return the cached value.
1751    ///
1752    /// # Returns
1753    ///
1754    /// A new memoized `BoxSupplier<T>`
1755    ///
1756    /// # Examples
1757    ///
1758    /// ```rust
1759    /// use prism3_function::{Supplier, FnSupplierOps};
1760    ///
1761    /// let mut call_count = 0;
1762    /// let mut memoized = (move || {
1763    ///     call_count += 1;
1764    ///     42
1765    /// }).memoize();
1766    ///
1767    /// assert_eq!(memoized.get(), 42); // Calls underlying function
1768    /// assert_eq!(memoized.get(), 42); // Returns cached value
1769    /// ```
1770    fn memoize(self) -> BoxSupplier<T>
1771    where
1772        T: Clone + 'static,
1773    {
1774        BoxSupplier::new(self).memoize()
1775    }
1776}
1777
1778// Implement the extension trait for all closures
1779impl<T, F> FnSupplierOps<T> for F where F: FnMut() -> T + Sized + 'static {}