prism3_function/
readonly_supplier.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2025.
4 *    3-Prism Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! # Read-only Supplier Types
10//!
11//! Provides read-only supplier implementations that generate and
12//! return values without modifying their own state.
13//!
14//! # Overview
15//!
16//! A **ReadonlySupplier** is a functional abstraction that
17//! generates values without accepting input or modifying its own
18//! state. Unlike `Supplier`, it uses `&self` instead of `&mut
19//! self`, enabling usage in read-only contexts and lock-free
20//! concurrent access.
21//!
22//! # Key Differences from Supplier
23//!
24//! | Aspect | Supplier | ReadonlySupplier |
25//! |--------|----------|------------------|
26//! | self signature | `&mut self` | `&self` |
27//! | Closure type | `FnMut() -> T` | `Fn() -> T` |
28//! | Can modify state | Yes | No |
29//! | Arc implementation | `Arc<Mutex<FnMut>>` | `Arc<Fn>` (lock-free!) |
30//! | Use cases | Counter, generator | Factory, constant, high concurrency |
31//!
32//! # Three Implementations
33//!
34//! - **`BoxReadonlySupplier<T>`**: Single ownership using `Box<dyn
35//!   Fn() -> T>`. Zero overhead, cannot be cloned. Best for
36//!   one-time use in read-only contexts.
37//!
38//! - **`ArcReadonlySupplier<T>`**: Thread-safe shared ownership
39//!   using `Arc<dyn Fn() -> T + Send + Sync>`. **Lock-free** - no
40//!   Mutex needed! Can be cloned and sent across threads with
41//!   excellent performance.
42//!
43//! - **`RcReadonlySupplier<T>`**: Single-threaded shared ownership
44//!   using `Rc<dyn Fn() -> T>`. Can be cloned but not sent across
45//!   threads. Lightweight alternative to `ArcReadonlySupplier`.
46//!
47//! # Use Cases
48//!
49//! ## 1. Calling in `&self` Methods
50//!
51//! ```rust
52//! use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
53//!
54//! struct Executor<E> {
55//!     error_supplier: ArcReadonlySupplier<E>,
56//! }
57//!
58//! impl<E> Executor<E> {
59//!     fn execute(&self) -> Result<(), E> {
60//!         // Can call directly in &self method!
61//!         Err(self.error_supplier.get())
62//!     }
63//! }
64//! ```
65//!
66//! ## 2. High-Concurrency Lock-Free Access
67//!
68//! ```rust
69//! use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
70//! use std::thread;
71//!
72//! let factory = ArcReadonlySupplier::new(|| {
73//!     String::from("Hello, World!")
74//! });
75//!
76//! let handles: Vec<_> = (0..10)
77//!     .map(|_| {
78//!         let f = factory.clone();
79//!         thread::spawn(move || f.get()) // Lock-free!
80//!     })
81//!     .collect();
82//!
83//! for h in handles {
84//!     assert_eq!(h.join().unwrap(), "Hello, World!");
85//! }
86//! ```
87//!
88//! ## 3. Fixed Factories
89//!
90//! ```rust
91//! use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
92//!
93//! #[derive(Clone)]
94//! struct Config {
95//!     timeout: u64,
96//! }
97//!
98//! let config_factory = BoxReadonlySupplier::new(|| Config {
99//!     timeout: 30,
100//! });
101//!
102//! assert_eq!(config_factory.get().timeout, 30);
103//! assert_eq!(config_factory.get().timeout, 30);
104//! ```
105//!
106//! # Performance Comparison
107//!
108//! For stateless scenarios in multi-threaded environments:
109//!
110//! - `ArcSupplier<T>`: Requires `Mutex`, lock contention on
111//!   every `get()` call
112//! - `ArcReadonlySupplier<T>`: Lock-free, can call `get()`
113//!   concurrently without contention
114//!
115//! Benchmark results show `ArcReadonlySupplier` can be **10x
116//! faster** than `ArcSupplier` in high-concurrency scenarios.
117//!
118//! # Author
119//!
120//! Haixing Hu
121
122use std::rc::Rc;
123use std::sync::Arc;
124
125use crate::transformer::Transformer;
126
127// ======================================================================
128// ReadonlySupplier Trait
129// ======================================================================
130
131/// Read-only supplier trait: generates values without modifying
132/// state.
133///
134/// The core abstraction for stateless value generation. Unlike
135/// `Supplier<T>`, it uses `&self` instead of `&mut self`, enabling
136/// usage in read-only contexts and lock-free concurrent access.
137///
138/// # Key Characteristics
139///
140/// - **No input parameters**: Pure value generation
141/// - **Read-only access**: Uses `&self`, doesn't modify state
142/// - **Returns ownership**: Returns `T` (not `&T`) to avoid
143///   lifetime issues
144/// - **Lock-free concurrency**: `Arc` implementation doesn't need
145///   `Mutex`
146///
147/// # Automatically Implemented for Closures
148///
149/// All `Fn() -> T` closures automatically implement this trait,
150/// enabling seamless integration with both raw closures and
151/// wrapped supplier types.
152///
153/// # Examples
154///
155/// ## Using with Generic Functions
156///
157/// ```rust
158/// use prism3_function::{ReadonlySupplier, BoxReadonlySupplier};
159///
160/// fn call_twice<S: ReadonlySupplier<i32>>(supplier: &S)
161///     -> (i32, i32)
162/// {
163///     (supplier.get(), supplier.get())
164/// }
165///
166/// let s = BoxReadonlySupplier::new(|| 42);
167/// assert_eq!(call_twice(&s), (42, 42));
168///
169/// let closure = || 100;
170/// assert_eq!(call_twice(&closure), (100, 100));
171/// ```
172///
173/// ## Stateless Factory
174///
175/// ```rust
176/// use prism3_function::ReadonlySupplier;
177///
178/// struct User {
179///     name: String,
180/// }
181///
182/// impl User {
183///     fn new() -> Self {
184///         User {
185///             name: String::from("Default"),
186///         }
187///     }
188/// }
189///
190/// let factory = || User::new();
191/// let user1 = factory.get();
192/// let user2 = factory.get();
193/// // Each call creates a new User instance
194/// ```
195///
196/// # Author
197///
198/// Haixing Hu
199pub trait ReadonlySupplier<T> {
200    /// Generates and returns a value.
201    ///
202    /// Executes the underlying function and returns the generated
203    /// value. Uses `&self` because the supplier doesn't modify its
204    /// own state.
205    ///
206    /// # Returns
207    ///
208    /// The generated value of type `T`
209    ///
210    /// # Examples
211    ///
212    /// ```rust
213    /// use prism3_function::{ReadonlySupplier, BoxReadonlySupplier};
214    ///
215    /// let supplier = BoxReadonlySupplier::new(|| 42);
216    /// assert_eq!(supplier.get(), 42);
217    /// assert_eq!(supplier.get(), 42);
218    /// ```
219    fn get(&self) -> T;
220
221    /// Converts to `BoxReadonlySupplier`.
222    ///
223    /// This method has a default implementation that wraps the
224    /// supplier in a `BoxReadonlySupplier`. Custom implementations
225    /// can override this method for optimization purposes.
226    ///
227    /// # Returns
228    ///
229    /// A new `BoxReadonlySupplier<T>` instance
230    ///
231    /// # Examples
232    ///
233    /// ```rust
234    /// use prism3_function::ReadonlySupplier;
235    ///
236    /// let closure = || 42;
237    /// let boxed = closure.into_box();
238    /// assert_eq!(boxed.get(), 42);
239    /// ```
240    fn into_box(self) -> BoxReadonlySupplier<T>
241    where
242        Self: Sized + 'static,
243        T: 'static,
244    {
245        BoxReadonlySupplier::new(move || self.get())
246    }
247
248    /// Converts to `RcReadonlySupplier`.
249    ///
250    /// This method has a default implementation that wraps the
251    /// supplier in an `RcReadonlySupplier`. Custom implementations
252    /// can override this method for optimization purposes.
253    ///
254    /// # Returns
255    ///
256    /// A new `RcReadonlySupplier<T>` instance
257    ///
258    /// # Examples
259    ///
260    /// ```rust
261    /// use prism3_function::ReadonlySupplier;
262    ///
263    /// let closure = || 42;
264    /// let rc = closure.into_rc();
265    /// assert_eq!(rc.get(), 42);
266    /// ```
267    fn into_rc(self) -> RcReadonlySupplier<T>
268    where
269        Self: Sized + 'static,
270        T: 'static,
271    {
272        RcReadonlySupplier::new(move || self.get())
273    }
274
275    /// Converts to `ArcReadonlySupplier`.
276    ///
277    /// This method has a default implementation that wraps the
278    /// supplier in an `ArcReadonlySupplier`. Custom implementations
279    /// can override this method for optimization purposes.
280    ///
281    /// # Returns
282    ///
283    /// A new `ArcReadonlySupplier<T>` instance
284    ///
285    /// # Examples
286    ///
287    /// ```rust
288    /// use prism3_function::ReadonlySupplier;
289    ///
290    /// let closure = || 42;
291    /// let arc = closure.into_arc();
292    /// assert_eq!(arc.get(), 42);
293    /// ```
294    fn into_arc(self) -> ArcReadonlySupplier<T>
295    where
296        Self: Sized + Send + Sync + 'static,
297        T: Send + 'static,
298    {
299        ArcReadonlySupplier::new(move || self.get())
300    }
301
302    /// Converts to a closure implementing `FnMut() -> T`.
303    ///
304    /// This method has a default implementation that wraps the
305    /// supplier in a closure. Custom implementations can override
306    /// this method for optimization purposes.
307    ///
308    /// # Returns
309    ///
310    /// A closure implementing `FnMut() -> T`
311    ///
312    /// # Examples
313    ///
314    /// ```rust
315    /// use prism3_function::ReadonlySupplier;
316    ///
317    /// let closure = || 42;
318    /// let mut fn_mut = closure.into_fn();
319    /// assert_eq!(fn_mut(), 42);
320    /// assert_eq!(fn_mut(), 42);
321    /// ```
322    fn into_fn(self) -> impl FnMut() -> T
323    where
324        Self: Sized,
325    {
326        move || self.get()
327    }
328
329    /// Converts to `BoxReadonlySupplier` by cloning.
330    ///
331    /// This method clones the supplier and wraps it in a
332    /// `BoxReadonlySupplier`. Requires `Self: Clone`. Custom
333    /// implementations can override this method for optimization.
334    ///
335    /// # Returns
336    ///
337    /// A new `BoxReadonlySupplier<T>` instance
338    ///
339    /// # Examples
340    ///
341    /// ```rust
342    /// use prism3_function::ReadonlySupplier;
343    ///
344    /// let closure = || 42;
345    /// let boxed = closure.to_box();
346    /// assert_eq!(boxed.get(), 42);
347    /// ```
348    fn to_box(&self) -> BoxReadonlySupplier<T>
349    where
350        Self: Clone + 'static,
351        T: 'static,
352    {
353        self.clone().into_box()
354    }
355
356    /// Converts to `RcReadonlySupplier` by cloning.
357    ///
358    /// This method clones the supplier and wraps it in an
359    /// `RcReadonlySupplier`. Requires `Self: Clone`. Custom
360    /// implementations can override this method for optimization.
361    ///
362    /// # Returns
363    ///
364    /// A new `RcReadonlySupplier<T>` instance
365    ///
366    /// # Examples
367    ///
368    /// ```rust
369    /// use prism3_function::ReadonlySupplier;
370    ///
371    /// let closure = || 42;
372    /// let rc = closure.to_rc();
373    /// assert_eq!(rc.get(), 42);
374    /// ```
375    fn to_rc(&self) -> RcReadonlySupplier<T>
376    where
377        Self: Clone + 'static,
378        T: 'static,
379    {
380        self.clone().into_rc()
381    }
382
383    /// Converts to `ArcReadonlySupplier` by cloning.
384    ///
385    /// This method clones the supplier and wraps it in an
386    /// `ArcReadonlySupplier`. Requires `Self: Clone + Send + Sync`.
387    /// Custom implementations can override this method for
388    /// optimization.
389    ///
390    /// # Returns
391    ///
392    /// A new `ArcReadonlySupplier<T>` instance
393    ///
394    /// # Examples
395    ///
396    /// ```rust
397    /// use prism3_function::ReadonlySupplier;
398    ///
399    /// let closure = || 42;
400    /// let arc = closure.to_arc();
401    /// assert_eq!(arc.get(), 42);
402    /// ```
403    fn to_arc(&self) -> ArcReadonlySupplier<T>
404    where
405        Self: Clone + Send + Sync + 'static,
406        T: Send + 'static,
407    {
408        self.clone().into_arc()
409    }
410
411    /// Converts to a closure by cloning.
412    ///
413    /// This method clones the supplier and wraps it in a closure
414    /// implementing `FnMut() -> T`. Requires `Self: Clone`. Custom
415    /// implementations can override this method for optimization.
416    ///
417    /// # Returns
418    ///
419    /// A closure implementing `FnMut() -> T`
420    ///
421    /// # Examples
422    ///
423    /// ```rust
424    /// use prism3_function::ReadonlySupplier;
425    ///
426    /// let closure = || 42;
427    /// let mut fn_mut = closure.to_fn();
428    /// assert_eq!(fn_mut(), 42);
429    /// assert_eq!(fn_mut(), 42);
430    /// ```
431    fn to_fn(&self) -> impl FnMut() -> T
432    where
433        Self: Clone,
434    {
435        self.clone().into_fn()
436    }
437}
438
439// ======================================================================
440// BoxReadonlySupplier - Single Ownership Implementation
441// ======================================================================
442
443/// Box-based single ownership read-only supplier.
444///
445/// Uses `Box<dyn Fn() -> T>` for single ownership scenarios. This
446/// is the most lightweight read-only supplier with zero reference
447/// counting overhead.
448///
449/// # Ownership Model
450///
451/// Methods consume `self` (move semantics) or borrow `&self` for
452/// read-only operations. When you call methods like `map()`, the
453/// original supplier is consumed and you get a new one:
454///
455/// ```rust
456/// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
457///
458/// let supplier = BoxReadonlySupplier::new(|| 10);
459/// let mapped = supplier.map(|x| x * 2);
460/// // supplier is no longer usable here
461/// ```
462///
463/// # Examples
464///
465/// ## Constant Factory
466///
467/// ```rust
468/// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
469///
470/// let factory = BoxReadonlySupplier::new(|| 42);
471/// assert_eq!(factory.get(), 42);
472/// assert_eq!(factory.get(), 42);
473/// ```
474///
475/// ## Method Chaining
476///
477/// ```rust
478/// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
479///
480/// let pipeline = BoxReadonlySupplier::new(|| 10)
481///     .map(|x| x * 2)
482///     .map(|x| x + 5);
483///
484/// assert_eq!(pipeline.get(), 25);
485/// ```
486///
487/// # Author
488///
489/// Haixing Hu
490pub struct BoxReadonlySupplier<T> {
491    function: Box<dyn Fn() -> T>,
492}
493
494impl<T> BoxReadonlySupplier<T>
495where
496    T: 'static,
497{
498    /// Creates a new `BoxReadonlySupplier`.
499    ///
500    /// # Parameters
501    ///
502    /// * `f` - The closure to wrap
503    ///
504    /// # Returns
505    ///
506    /// A new `BoxReadonlySupplier<T>` instance
507    ///
508    /// # Examples
509    ///
510    /// ```rust
511    /// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
512    ///
513    /// let supplier = BoxReadonlySupplier::new(|| 42);
514    /// assert_eq!(supplier.get(), 42);
515    /// ```
516    pub fn new<F>(f: F) -> Self
517    where
518        F: Fn() -> T + 'static,
519    {
520        BoxReadonlySupplier {
521            function: Box::new(f),
522        }
523    }
524
525    /// Creates a constant supplier.
526    ///
527    /// Returns a supplier that always produces the same value (via
528    /// cloning).
529    ///
530    /// # Parameters
531    ///
532    /// * `value` - The constant value to return
533    ///
534    /// # Returns
535    ///
536    /// A constant supplier
537    ///
538    /// # Examples
539    ///
540    /// ```rust
541    /// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
542    ///
543    /// let constant = BoxReadonlySupplier::constant(42);
544    /// assert_eq!(constant.get(), 42);
545    /// assert_eq!(constant.get(), 42);
546    /// ```
547    pub fn constant(value: T) -> Self
548    where
549        T: Clone + 'static,
550    {
551        BoxReadonlySupplier::new(move || value.clone())
552    }
553
554    /// Maps the output using a transformation function.
555    ///
556    /// Consumes self and returns a new supplier that applies the
557    /// mapper to each output.
558    ///
559    /// # Parameters
560    ///
561    /// * `mapper` - The transformer to apply to the output. Can be a
562    ///   closure, function pointer, or any type implementing
563    ///   `Transformer<T, U>`.
564    ///
565    /// # Returns
566    ///
567    /// A new mapped `BoxReadonlySupplier<U>`
568    ///
569    /// # Examples
570    ///
571    /// ```rust
572    /// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
573    ///
574    /// let mapped = BoxReadonlySupplier::new(|| 10)
575    ///     .map(|x| x * 2)
576    ///     .map(|x| x + 5);
577    /// assert_eq!(mapped.get(), 25);
578    /// ```
579    pub fn map<U, M>(self, mapper: M) -> BoxReadonlySupplier<U>
580    where
581        M: Transformer<T, U> + 'static,
582        U: 'static,
583    {
584        BoxReadonlySupplier::new(move || mapper.apply(self.get()))
585    }
586
587    /// Filters output based on a predicate.
588    ///
589    /// Returns a new supplier that returns `Some(value)` if the
590    /// predicate is satisfied, `None` otherwise.
591    ///
592    /// # Parameters
593    ///
594    /// * `predicate` - The predicate to test the supplied value
595    ///
596    /// # Returns
597    ///
598    /// A new filtered `BoxReadonlySupplier<Option<T>>`
599    ///
600    /// # Examples
601    ///
602    /// ```rust
603    /// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
604    ///
605    /// let filtered = BoxReadonlySupplier::new(|| 42)
606    ///     .filter(|x| x % 2 == 0);
607    ///
608    /// assert_eq!(filtered.get(), Some(42));
609    /// ```
610    pub fn filter<P>(self, predicate: P) -> BoxReadonlySupplier<Option<T>>
611    where
612        P: Fn(&T) -> bool + 'static,
613    {
614        BoxReadonlySupplier::new(move || {
615            let value = self.get();
616            if predicate(&value) {
617                Some(value)
618            } else {
619                None
620            }
621        })
622    }
623
624    /// Combines this supplier with another, producing a tuple.
625    ///
626    /// Consumes both suppliers and returns a new supplier that
627    /// produces `(T, U)` tuples.
628    ///
629    /// # Parameters
630    ///
631    /// * `other` - The other supplier to combine with
632    ///
633    /// # Returns
634    ///
635    /// A new `BoxReadonlySupplier<(T, U)>`
636    ///
637    /// # Examples
638    ///
639    /// ```rust
640    /// use prism3_function::{BoxReadonlySupplier, ReadonlySupplier};
641    ///
642    /// let first = BoxReadonlySupplier::new(|| 42);
643    /// let second = BoxReadonlySupplier::new(|| "hello");
644    /// let zipped = first.zip(second);
645    ///
646    /// assert_eq!(zipped.get(), (42, "hello"));
647    /// ```
648    pub fn zip<U>(self, other: BoxReadonlySupplier<U>) -> BoxReadonlySupplier<(T, U)>
649    where
650        U: 'static,
651    {
652        BoxReadonlySupplier::new(move || (self.get(), other.get()))
653    }
654}
655
656impl<T> ReadonlySupplier<T> for BoxReadonlySupplier<T> {
657    fn get(&self) -> T {
658        (self.function)()
659    }
660
661    fn into_box(self) -> BoxReadonlySupplier<T>
662    where
663        T: 'static,
664    {
665        self
666    }
667
668    fn into_rc(self) -> RcReadonlySupplier<T>
669    where
670        T: 'static,
671    {
672        RcReadonlySupplier::new(self.function)
673    }
674
675    // do NOT override BoxReadonlySupplier::to_arc() because BoxReadonlySupplier
676    // is not Send + Sync and calling BoxReadonlySupplier::to_arc() will cause a compile error
677
678    fn into_fn(self) -> impl FnMut() -> T {
679        move || (self.function)()
680    }
681
682    // Note: to_box, to_rc, to_arc, and to_fn cannot be implemented
683    // for BoxReadonlySupplier because it does not implement Clone.
684    // Box provides unique ownership and cannot be cloned unless
685    // the inner type implements Clone, which dyn Fn() -> T does not.
686    //
687    // If you call these methods on BoxReadonlySupplier, the compiler
688    // will fail with an error indicating that BoxReadonlySupplier<T>
689    // does not implement Clone, which is required by the default
690    // implementations of to_box, to_rc, to_arc, and to_fn.
691}
692
693// ======================================================================
694// ArcReadonlySupplier - Thread-safe Shared Ownership Implementation
695// ======================================================================
696
697/// Thread-safe shared ownership read-only supplier.
698///
699/// Uses `Arc<dyn Fn() -> T + Send + Sync>` for thread-safe shared
700/// ownership. **Lock-free** - no `Mutex` needed! Can be cloned and
701/// sent across threads with excellent concurrent performance.
702///
703/// # Ownership Model
704///
705/// Methods borrow `&self` instead of consuming `self`. The
706/// original supplier remains usable after method calls:
707///
708/// ```rust
709/// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
710///
711/// let source = ArcReadonlySupplier::new(|| 10);
712/// let mapped = source.map(|x| x * 2);
713/// // source is still usable here!
714/// ```
715///
716/// # Lock-Free Performance
717///
718/// Unlike `ArcSupplier`, this implementation doesn't need `Mutex`.
719/// Multiple threads can call `get()` concurrently without lock
720/// contention, making it ideal for high-concurrency scenarios.
721///
722/// # Examples
723///
724/// ## Thread-safe Factory
725///
726/// ```rust
727/// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
728/// use std::thread;
729///
730/// let factory = ArcReadonlySupplier::new(|| {
731///     String::from("Hello")
732/// });
733///
734/// let f1 = factory.clone();
735/// let f2 = factory.clone();
736///
737/// let h1 = thread::spawn(move || f1.get());
738/// let h2 = thread::spawn(move || f2.get());
739///
740/// assert_eq!(h1.join().unwrap(), "Hello");
741/// assert_eq!(h2.join().unwrap(), "Hello");
742/// ```
743///
744/// ## Reusable Transformations
745///
746/// ```rust
747/// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
748///
749/// let base = ArcReadonlySupplier::new(|| 10);
750/// let doubled = base.map(|x| x * 2);
751/// let tripled = base.map(|x| x * 3);
752///
753/// // All remain usable
754/// assert_eq!(base.get(), 10);
755/// assert_eq!(doubled.get(), 20);
756/// assert_eq!(tripled.get(), 30);
757/// ```
758///
759/// # Author
760///
761/// Haixing Hu
762pub struct ArcReadonlySupplier<T> {
763    function: Arc<dyn Fn() -> T + Send + Sync>,
764}
765
766impl<T> ArcReadonlySupplier<T>
767where
768    T: Send + 'static,
769{
770    /// Creates a new `ArcReadonlySupplier`.
771    ///
772    /// # Parameters
773    ///
774    /// * `f` - The closure to wrap
775    ///
776    /// # Returns
777    ///
778    /// A new `ArcReadonlySupplier<T>` instance
779    ///
780    /// # Examples
781    ///
782    /// ```rust
783    /// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
784    ///
785    /// let supplier = ArcReadonlySupplier::new(|| 42);
786    /// assert_eq!(supplier.get(), 42);
787    /// ```
788    pub fn new<F>(f: F) -> Self
789    where
790        F: Fn() -> T + Send + Sync + 'static,
791    {
792        ArcReadonlySupplier {
793            function: Arc::new(f),
794        }
795    }
796
797    /// Creates a constant supplier.
798    ///
799    /// # Parameters
800    ///
801    /// * `value` - The constant value to return
802    ///
803    /// # Returns
804    ///
805    /// A constant supplier
806    ///
807    /// # Examples
808    ///
809    /// ```rust
810    /// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
811    ///
812    /// let constant = ArcReadonlySupplier::constant(42);
813    /// assert_eq!(constant.get(), 42);
814    /// assert_eq!(constant.get(), 42);
815    /// ```
816    pub fn constant(value: T) -> Self
817    where
818        T: Clone + Send + Sync + 'static,
819    {
820        ArcReadonlySupplier::new(move || value.clone())
821    }
822
823    /// Maps the output using a transformation function.
824    ///
825    /// Borrows `&self`, doesn't consume the original supplier.
826    ///
827    /// # Parameters
828    ///
829    /// * `mapper` - The transformer to apply to the output. Can be a
830    ///   closure, function pointer, or any type implementing
831    ///   `Transformer<T, U>`.
832    ///
833    /// # Returns
834    ///
835    /// A new mapped `ArcReadonlySupplier<U>`
836    ///
837    /// # Examples
838    ///
839    /// ```rust
840    /// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
841    ///
842    /// let source = ArcReadonlySupplier::new(|| 10);
843    /// let mapped = source.map(|x| x * 2);
844    /// // source is still usable
845    /// assert_eq!(mapped.get(), 20);
846    /// ```
847    pub fn map<U, M>(&self, mapper: M) -> ArcReadonlySupplier<U>
848    where
849        M: Transformer<T, U> + Send + Sync + 'static,
850        U: Send + 'static,
851    {
852        let self_fn = Arc::clone(&self.function);
853        let mapper = Arc::new(mapper);
854        ArcReadonlySupplier {
855            function: Arc::new(move || {
856                let value = self_fn();
857                mapper.apply(value)
858            }),
859        }
860    }
861
862    /// Filters output based on a predicate.
863    ///
864    /// # Parameters
865    ///
866    /// * `predicate` - The predicate to test the supplied value
867    ///
868    /// # Returns
869    ///
870    /// A new filtered `ArcReadonlySupplier<Option<T>>`
871    ///
872    /// # Examples
873    ///
874    /// ```rust
875    /// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
876    ///
877    /// let source = ArcReadonlySupplier::new(|| 42);
878    /// let filtered = source.filter(|x| x % 2 == 0);
879    ///
880    /// assert_eq!(filtered.get(), Some(42));
881    /// ```
882    pub fn filter<P>(&self, predicate: P) -> ArcReadonlySupplier<Option<T>>
883    where
884        P: Fn(&T) -> bool + Send + Sync + 'static,
885    {
886        let self_fn = Arc::clone(&self.function);
887        let predicate = Arc::new(predicate);
888        ArcReadonlySupplier {
889            function: Arc::new(move || {
890                let value = self_fn();
891                if predicate(&value) {
892                    Some(value)
893                } else {
894                    None
895                }
896            }),
897        }
898    }
899
900    /// Combines this supplier with another, producing a tuple.
901    ///
902    /// # Parameters
903    ///
904    /// * `other` - The other supplier to combine with. **Note:
905    ///   Passed by reference, so the original supplier remains
906    ///   usable.**
907    ///
908    /// # Returns
909    ///
910    /// A new `ArcReadonlySupplier<(T, U)>`
911    ///
912    /// # Examples
913    ///
914    /// ```rust
915    /// use prism3_function::{ArcReadonlySupplier, ReadonlySupplier};
916    ///
917    /// let first = ArcReadonlySupplier::new(|| 42);
918    /// let second = ArcReadonlySupplier::new(|| "hello");
919    ///
920    /// // second is passed by reference, so it remains usable
921    /// let zipped = first.zip(&second);
922    ///
923    /// assert_eq!(zipped.get(), (42, "hello"));
924    ///
925    /// // Both first and second still usable
926    /// assert_eq!(first.get(), 42);
927    /// assert_eq!(second.get(), "hello");
928    /// ```
929    pub fn zip<U>(&self, other: &ArcReadonlySupplier<U>) -> ArcReadonlySupplier<(T, U)>
930    where
931        U: Send + 'static,
932    {
933        let first = Arc::clone(&self.function);
934        let second = Arc::clone(&other.function);
935        ArcReadonlySupplier {
936            function: Arc::new(move || (first(), second())),
937        }
938    }
939}
940
941impl<T> ReadonlySupplier<T> for ArcReadonlySupplier<T> {
942    fn get(&self) -> T {
943        (self.function)()
944    }
945
946    fn into_box(self) -> BoxReadonlySupplier<T>
947    where
948        T: 'static,
949    {
950        BoxReadonlySupplier::new(move || (self.function)())
951    }
952
953    fn into_rc(self) -> RcReadonlySupplier<T>
954    where
955        T: 'static,
956    {
957        RcReadonlySupplier::new(move || (self.function)())
958    }
959
960    fn into_arc(self) -> ArcReadonlySupplier<T>
961    where
962        T: Send + 'static,
963    {
964        self
965    }
966
967    fn into_fn(self) -> impl FnMut() -> T {
968        move || (self.function)()
969    }
970
971    // Optimized implementations using Arc::clone instead of
972    // wrapping in a closure
973
974    fn to_box(&self) -> BoxReadonlySupplier<T>
975    where
976        Self: Clone + 'static,
977        T: 'static,
978    {
979        let self_fn = self.function.clone();
980        BoxReadonlySupplier::new(move || self_fn())
981    }
982
983    fn to_rc(&self) -> RcReadonlySupplier<T>
984    where
985        Self: Clone + 'static,
986        T: 'static,
987    {
988        let self_fn = self.function.clone();
989        RcReadonlySupplier::new(move || self_fn())
990    }
991
992    fn to_arc(&self) -> ArcReadonlySupplier<T>
993    where
994        Self: Clone + Send + Sync + 'static,
995        T: Send + 'static,
996    {
997        self.clone()
998    }
999
1000    fn to_fn(&self) -> impl FnMut() -> T
1001    where
1002        Self: Clone,
1003    {
1004        let self_fn = self.function.clone();
1005        move || self_fn()
1006    }
1007}
1008
1009impl<T> Clone for ArcReadonlySupplier<T> {
1010    /// Clones the `ArcReadonlySupplier`.
1011    ///
1012    /// Creates a new instance that shares the underlying function
1013    /// with the original.
1014    fn clone(&self) -> Self {
1015        Self {
1016            function: Arc::clone(&self.function),
1017        }
1018    }
1019}
1020
1021// ======================================================================
1022// RcReadonlySupplier - Single-threaded Shared Ownership
1023// ======================================================================
1024
1025/// Single-threaded shared ownership read-only supplier.
1026///
1027/// Uses `Rc<dyn Fn() -> T>` for single-threaded shared ownership.
1028/// Can be cloned but not sent across threads.
1029///
1030/// # Ownership Model
1031///
1032/// Like `ArcReadonlySupplier`, methods borrow `&self` instead of
1033/// consuming `self`:
1034///
1035/// ```rust
1036/// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1037///
1038/// let source = RcReadonlySupplier::new(|| 10);
1039/// let mapped = source.map(|x| x * 2);
1040/// // source is still usable here!
1041/// ```
1042///
1043/// # Examples
1044///
1045/// ## Shared Factory
1046///
1047/// ```rust
1048/// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1049///
1050/// let factory = RcReadonlySupplier::new(|| {
1051///     String::from("Hello")
1052/// });
1053///
1054/// let f1 = factory.clone();
1055/// let f2 = factory.clone();
1056/// assert_eq!(f1.get(), "Hello");
1057/// assert_eq!(f2.get(), "Hello");
1058/// ```
1059///
1060/// ## Reusable Transformations
1061///
1062/// ```rust
1063/// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1064///
1065/// let base = RcReadonlySupplier::new(|| 10);
1066/// let doubled = base.map(|x| x * 2);
1067/// let tripled = base.map(|x| x * 3);
1068///
1069/// assert_eq!(base.get(), 10);
1070/// assert_eq!(doubled.get(), 20);
1071/// assert_eq!(tripled.get(), 30);
1072/// ```
1073///
1074/// # Author
1075///
1076/// Haixing Hu
1077pub struct RcReadonlySupplier<T> {
1078    function: Rc<dyn Fn() -> T>,
1079}
1080
1081impl<T> RcReadonlySupplier<T>
1082where
1083    T: 'static,
1084{
1085    /// Creates a new `RcReadonlySupplier`.
1086    ///
1087    /// # Parameters
1088    ///
1089    /// * `f` - The closure to wrap
1090    ///
1091    /// # Returns
1092    ///
1093    /// A new `RcReadonlySupplier<T>` instance
1094    ///
1095    /// # Examples
1096    ///
1097    /// ```rust
1098    /// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1099    ///
1100    /// let supplier = RcReadonlySupplier::new(|| 42);
1101    /// assert_eq!(supplier.get(), 42);
1102    /// ```
1103    pub fn new<F>(f: F) -> Self
1104    where
1105        F: Fn() -> T + 'static,
1106    {
1107        RcReadonlySupplier {
1108            function: Rc::new(f),
1109        }
1110    }
1111
1112    /// Creates a constant supplier.
1113    ///
1114    /// # Parameters
1115    ///
1116    /// * `value` - The constant value to return
1117    ///
1118    /// # Returns
1119    ///
1120    /// A constant supplier
1121    ///
1122    /// # Examples
1123    ///
1124    /// ```rust
1125    /// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1126    ///
1127    /// let constant = RcReadonlySupplier::constant(42);
1128    /// assert_eq!(constant.get(), 42);
1129    /// assert_eq!(constant.get(), 42);
1130    /// ```
1131    pub fn constant(value: T) -> Self
1132    where
1133        T: Clone + 'static,
1134    {
1135        RcReadonlySupplier::new(move || value.clone())
1136    }
1137
1138    /// Maps the output using a transformation function.
1139    ///
1140    /// Borrows `&self`, doesn't consume the original supplier.
1141    ///
1142    /// # Parameters
1143    ///
1144    /// * `mapper` - The transformer to apply to the output. Can be a
1145    ///   closure, function pointer, or any type implementing
1146    ///   `Transformer<T, U>`.
1147    ///
1148    /// # Returns
1149    ///
1150    /// A new mapped `RcReadonlySupplier<U>`
1151    ///
1152    /// # Examples
1153    ///
1154    /// ```rust
1155    /// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1156    ///
1157    /// let source = RcReadonlySupplier::new(|| 10);
1158    /// let mapped = source.map(|x| x * 2);
1159    /// // source is still usable
1160    /// assert_eq!(mapped.get(), 20);
1161    /// ```
1162    pub fn map<U, M>(&self, mapper: M) -> RcReadonlySupplier<U>
1163    where
1164        M: Transformer<T, U> + 'static,
1165        U: 'static,
1166    {
1167        let self_fn = Rc::clone(&self.function);
1168        let mapper = Rc::new(mapper);
1169        RcReadonlySupplier {
1170            function: Rc::new(move || {
1171                let value = self_fn();
1172                mapper.apply(value)
1173            }),
1174        }
1175    }
1176
1177    /// Filters output based on a predicate.
1178    ///
1179    /// # Parameters
1180    ///
1181    /// * `predicate` - The predicate to test the supplied value
1182    ///
1183    /// # Returns
1184    ///
1185    /// A new filtered `RcReadonlySupplier<Option<T>>`
1186    ///
1187    /// # Examples
1188    ///
1189    /// ```rust
1190    /// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1191    ///
1192    /// let source = RcReadonlySupplier::new(|| 42);
1193    /// let filtered = source.filter(|x| x % 2 == 0);
1194    ///
1195    /// assert_eq!(filtered.get(), Some(42));
1196    /// ```
1197    pub fn filter<P>(&self, predicate: P) -> RcReadonlySupplier<Option<T>>
1198    where
1199        P: Fn(&T) -> bool + 'static,
1200    {
1201        let self_fn = Rc::clone(&self.function);
1202        let predicate = Rc::new(predicate);
1203        RcReadonlySupplier {
1204            function: Rc::new(move || {
1205                let value = self_fn();
1206                if predicate(&value) {
1207                    Some(value)
1208                } else {
1209                    None
1210                }
1211            }),
1212        }
1213    }
1214
1215    /// Combines this supplier with another, producing a tuple.
1216    ///
1217    /// # Parameters
1218    ///
1219    /// * `other` - The other supplier to combine with. **Note:
1220    ///   Passed by reference, so the original supplier remains
1221    ///   usable.**
1222    ///
1223    /// # Returns
1224    ///
1225    /// A new `RcReadonlySupplier<(T, U)>`
1226    ///
1227    /// # Examples
1228    ///
1229    /// ```rust
1230    /// use prism3_function::{RcReadonlySupplier, ReadonlySupplier};
1231    ///
1232    /// let first = RcReadonlySupplier::new(|| 42);
1233    /// let second = RcReadonlySupplier::new(|| "hello");
1234    ///
1235    /// // second is passed by reference, so it remains usable
1236    /// let zipped = first.zip(&second);
1237    ///
1238    /// assert_eq!(zipped.get(), (42, "hello"));
1239    ///
1240    /// // Both first and second still usable
1241    /// assert_eq!(first.get(), 42);
1242    /// assert_eq!(second.get(), "hello");
1243    /// ```
1244    pub fn zip<U>(&self, other: &RcReadonlySupplier<U>) -> RcReadonlySupplier<(T, U)>
1245    where
1246        U: 'static,
1247    {
1248        let first = Rc::clone(&self.function);
1249        let second = Rc::clone(&other.function);
1250        RcReadonlySupplier {
1251            function: Rc::new(move || (first(), second())),
1252        }
1253    }
1254}
1255
1256impl<T> ReadonlySupplier<T> for RcReadonlySupplier<T> {
1257    fn get(&self) -> T {
1258        (self.function)()
1259    }
1260
1261    fn into_box(self) -> BoxReadonlySupplier<T>
1262    where
1263        T: 'static,
1264    {
1265        BoxReadonlySupplier::new(move || (self.function)())
1266    }
1267
1268    fn into_rc(self) -> RcReadonlySupplier<T>
1269    where
1270        T: 'static,
1271    {
1272        self
1273    }
1274
1275    // do NOT override RcReadonlySupplier::to_arc() because RcReadonlySupplier
1276    // is not Send + Sync and calling RcReadonlySupplier::to_arc() will cause a compile error
1277
1278    fn into_fn(self) -> impl FnMut() -> T {
1279        move || (self.function)()
1280    }
1281
1282    // Optimized implementations using Rc::clone instead of wrapping
1283    // in a closure
1284
1285    fn to_box(&self) -> BoxReadonlySupplier<T>
1286    where
1287        Self: Clone + 'static,
1288        T: 'static,
1289    {
1290        let self_fn = self.function.clone();
1291        BoxReadonlySupplier::new(move || self_fn())
1292    }
1293
1294    fn to_rc(&self) -> RcReadonlySupplier<T>
1295    where
1296        Self: Clone + 'static,
1297        T: 'static,
1298    {
1299        self.clone()
1300    }
1301
1302    // Note: to_arc cannot be implemented for RcReadonlySupplier
1303    // because Rc is not Send + Sync, which is required for
1304    // ArcReadonlySupplier.
1305    //
1306    // If you call to_arc on RcReadonlySupplier, the compiler will
1307    // fail with an error indicating that RcReadonlySupplier<T> does
1308    // not satisfy the Send + Sync bounds required by the default
1309    // implementation of to_arc.
1310
1311    fn to_fn(&self) -> impl FnMut() -> T
1312    where
1313        Self: Clone,
1314    {
1315        let self_fn = self.function.clone();
1316        move || self_fn()
1317    }
1318}
1319
1320impl<T> Clone for RcReadonlySupplier<T> {
1321    /// Clones the `RcReadonlySupplier`.
1322    ///
1323    /// Creates a new instance that shares the underlying function
1324    /// with the original.
1325    fn clone(&self) -> Self {
1326        Self {
1327            function: Rc::clone(&self.function),
1328        }
1329    }
1330}
1331
1332// ======================================================================
1333// Implement ReadonlySupplier for Closures
1334// ======================================================================
1335
1336impl<T, F> ReadonlySupplier<T> for F
1337where
1338    F: Fn() -> T,
1339{
1340    fn get(&self) -> T {
1341        self()
1342    }
1343
1344    // Use optimized implementations for closures instead of the
1345    // default implementations. This avoids double wrapping by
1346    // directly creating the target type.
1347
1348    fn into_box(self) -> BoxReadonlySupplier<T>
1349    where
1350        Self: Sized + 'static,
1351        T: 'static,
1352    {
1353        BoxReadonlySupplier::new(self)
1354    }
1355
1356    fn into_rc(self) -> RcReadonlySupplier<T>
1357    where
1358        Self: Sized + 'static,
1359        T: 'static,
1360    {
1361        RcReadonlySupplier::new(self)
1362    }
1363
1364    fn into_arc(self) -> ArcReadonlySupplier<T>
1365    where
1366        Self: Sized + Send + Sync + 'static,
1367        T: Send + 'static,
1368    {
1369        ArcReadonlySupplier::new(self)
1370    }
1371
1372    fn into_fn(self) -> impl FnMut() -> T
1373    where
1374        Self: Sized,
1375    {
1376        self
1377    }
1378
1379    // Optimized implementations for to_* methods
1380
1381    fn to_box(&self) -> BoxReadonlySupplier<T>
1382    where
1383        Self: Clone + 'static,
1384        T: 'static,
1385    {
1386        let self_fn = self.clone();
1387        BoxReadonlySupplier::new(self_fn)
1388    }
1389
1390    fn to_rc(&self) -> RcReadonlySupplier<T>
1391    where
1392        Self: Clone + 'static,
1393        T: 'static,
1394    {
1395        let self_fn = self.clone();
1396        RcReadonlySupplier::new(self_fn)
1397    }
1398
1399    fn to_arc(&self) -> ArcReadonlySupplier<T>
1400    where
1401        Self: Clone + Send + Sync + 'static,
1402        T: Send + 'static,
1403    {
1404        let self_fn = self.clone();
1405        ArcReadonlySupplier::new(self_fn)
1406    }
1407
1408    fn to_fn(&self) -> impl FnMut() -> T
1409    where
1410        Self: Clone,
1411    {
1412        self.clone()
1413    }
1414}
1415
1416// ======================================================================
1417// Note on Extension Traits for Closures
1418// ======================================================================
1419//
1420// We don't provide `FnReadonlySupplierOps` trait for `Fn() -> T` closures
1421// because:
1422//
1423// 1. All `Fn` closures also implement `FnMut`, so they can use `FnSupplierOps`
1424//    from the `supplier` module
1425// 2. Providing both would cause ambiguity errors due to overlapping trait impls
1426// 3. Rust doesn't support negative trait bounds to exclude `FnMut`
1427//
1428// Users of `Fn` closures should use `FnSupplierOps` from `supplier` module,
1429// or explicitly convert to `BoxReadonlySupplier` using `.into_box()` first.