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
124// ==========================================================================
125// Supplier Trait
126// ==========================================================================
127
128/// Supplier trait: generates and returns values without input.
129///
130/// The core abstraction for value generation. Similar to Java's
131/// `Supplier<T>` interface, it produces values without taking any
132/// input parameters.
133///
134/// # Key Characteristics
135///
136/// - **No input parameters**: Pure value generation
137/// - **Mutable access**: Uses `&mut self` to allow state changes
138/// - **Returns ownership**: Returns `T` (not `&T`) to avoid lifetime
139/// issues
140/// - **Can modify state**: Commonly used for counters, sequences,
141/// and generators
142///
143/// # Automatically Implemented for Closures
144///
145/// All `FnMut() -> T` closures automatically implement this trait,
146/// enabling seamless integration with both raw closures and wrapped
147/// supplier types.
148///
149/// # Examples
150///
151/// ## Using with Generic Functions
152///
153/// ```rust
154/// use prism3_function::{Supplier, BoxSupplier};
155///
156/// fn call_twice<S: Supplier<i32>>(supplier: &mut S) -> (i32, i32) {
157/// (supplier.get(), supplier.get())
158/// }
159///
160/// let mut s = BoxSupplier::new(|| 42);
161/// assert_eq!(call_twice(&mut s), (42, 42));
162///
163/// let mut closure = || 100;
164/// assert_eq!(call_twice(&mut closure), (100, 100));
165/// ```
166///
167/// ## Stateful Supplier
168///
169/// ```rust
170/// use prism3_function::Supplier;
171///
172/// let mut counter = 0;
173/// let mut stateful = || {
174/// counter += 1;
175/// counter
176/// };
177///
178/// assert_eq!(stateful.get(), 1);
179/// assert_eq!(stateful.get(), 2);
180/// ```
181///
182/// # Author
183///
184/// Haixing Hu
185pub trait Supplier<T> {
186 /// Generates and returns the next value.
187 ///
188 /// Executes the underlying function and returns the generated
189 /// value. Uses `&mut self` because suppliers typically involve
190 /// state changes (counters, sequences, etc.).
191 ///
192 /// # Returns
193 ///
194 /// The generated value of type `T`
195 ///
196 /// # Examples
197 ///
198 /// ```rust
199 /// use prism3_function::{Supplier, BoxSupplier};
200 ///
201 /// let mut supplier = BoxSupplier::new(|| 42);
202 /// assert_eq!(supplier.get(), 42);
203 /// ```
204 fn get(&mut self) -> T;
205
206 /// Converts to `BoxSupplier`.
207 ///
208 /// # Returns
209 ///
210 /// A new `BoxSupplier<T>` instance
211 ///
212 /// # Examples
213 ///
214 /// ```rust
215 /// use prism3_function::Supplier;
216 ///
217 /// let closure = || 42;
218 /// let mut boxed = closure.into_box();
219 /// assert_eq!(boxed.get(), 42);
220 /// ```
221 fn into_box(self) -> BoxSupplier<T>
222 where
223 Self: Sized + 'static,
224 T: 'static;
225
226 /// Converts to `RcSupplier`.
227 ///
228 /// # Returns
229 ///
230 /// A new `RcSupplier<T>` instance
231 ///
232 /// # Examples
233 ///
234 /// ```rust
235 /// use prism3_function::Supplier;
236 ///
237 /// let closure = || 42;
238 /// let mut rc = closure.into_rc();
239 /// assert_eq!(rc.get(), 42);
240 /// ```
241 fn into_rc(self) -> RcSupplier<T>
242 where
243 Self: Sized + 'static,
244 T: 'static;
245
246 /// Converts to `ArcSupplier`.
247 ///
248 /// # Returns
249 ///
250 /// A new `ArcSupplier<T>` instance
251 ///
252 /// # Examples
253 ///
254 /// ```rust
255 /// use prism3_function::Supplier;
256 ///
257 /// let closure = || 42;
258 /// let mut arc = closure.into_arc();
259 /// assert_eq!(arc.get(), 42);
260 /// ```
261 fn into_arc(self) -> ArcSupplier<T>
262 where
263 Self: Sized + Send + 'static,
264 T: Send + 'static;
265}
266
267// ==========================================================================
268// Implement Supplier for Closures
269// ==========================================================================
270
271impl<T, F> Supplier<T> for F
272where
273 F: FnMut() -> T,
274{
275 fn get(&mut self) -> T {
276 self()
277 }
278
279 fn into_box(self) -> BoxSupplier<T>
280 where
281 Self: Sized + 'static,
282 T: 'static,
283 {
284 BoxSupplier::new(self)
285 }
286
287 fn into_rc(self) -> RcSupplier<T>
288 where
289 Self: Sized + 'static,
290 T: 'static,
291 {
292 RcSupplier::new(self)
293 }
294
295 fn into_arc(self) -> ArcSupplier<T>
296 where
297 Self: Sized + Send + 'static,
298 T: Send + 'static,
299 {
300 ArcSupplier::new(self)
301 }
302}
303
304// ==========================================================================
305// BoxSupplier - Single Ownership Implementation
306// ==========================================================================
307
308/// Box-based single ownership supplier.
309///
310/// Uses `Box<dyn FnMut() -> T>` for single ownership scenarios.
311/// This is the most lightweight supplier with zero reference
312/// counting overhead.
313///
314/// # Ownership Model
315///
316/// Methods consume `self` (move semantics). When you call a method
317/// like `map()`, the original supplier is consumed and you get a new
318/// one:
319///
320/// ```rust
321/// use prism3_function::{BoxSupplier, Supplier};
322///
323/// let supplier = BoxSupplier::new(|| 10);
324/// let mapped = supplier.map(|x| x * 2);
325/// // supplier is no longer usable here
326/// ```
327///
328/// # Examples
329///
330/// ## Counter
331///
332/// ```rust
333/// use prism3_function::{BoxSupplier, Supplier};
334///
335/// let mut counter = 0;
336/// let mut supplier = BoxSupplier::new(move || {
337/// counter += 1;
338/// counter
339/// });
340///
341/// assert_eq!(supplier.get(), 1);
342/// assert_eq!(supplier.get(), 2);
343/// ```
344///
345/// ## Method Chaining
346///
347/// ```rust
348/// use prism3_function::{BoxSupplier, Supplier};
349///
350/// let mut pipeline = BoxSupplier::new(|| 10)
351/// .map(|x| x * 2)
352/// .map(|x| x + 5);
353///
354/// assert_eq!(pipeline.get(), 25);
355/// ```
356///
357/// # Author
358///
359/// Haixing Hu
360pub struct BoxSupplier<T> {
361 function: Box<dyn FnMut() -> T>,
362}
363
364impl<T> BoxSupplier<T>
365where
366 T: 'static,
367{
368 /// Creates a new `BoxSupplier`.
369 ///
370 /// # Parameters
371 ///
372 /// * `f` - The closure to wrap
373 ///
374 /// # Returns
375 ///
376 /// A new `BoxSupplier<T>` instance
377 ///
378 /// # Examples
379 ///
380 /// ```rust
381 /// use prism3_function::{BoxSupplier, Supplier};
382 ///
383 /// let mut supplier = BoxSupplier::new(|| 42);
384 /// assert_eq!(supplier.get(), 42);
385 /// ```
386 pub fn new<F>(f: F) -> Self
387 where
388 F: FnMut() -> T + 'static,
389 {
390 BoxSupplier {
391 function: Box::new(f),
392 }
393 }
394
395 /// Creates a constant supplier.
396 ///
397 /// Returns a supplier that always produces the same value (via
398 /// cloning).
399 ///
400 /// # Parameters
401 ///
402 /// * `value` - The constant value to return
403 ///
404 /// # Returns
405 ///
406 /// A constant supplier
407 ///
408 /// # Examples
409 ///
410 /// ```rust
411 /// use prism3_function::{BoxSupplier, Supplier};
412 ///
413 /// let mut constant = BoxSupplier::constant(42);
414 /// assert_eq!(constant.get(), 42);
415 /// assert_eq!(constant.get(), 42);
416 /// ```
417 pub fn constant(value: T) -> Self
418 where
419 T: Clone + 'static,
420 {
421 BoxSupplier::new(move || value.clone())
422 }
423
424 /// Maps the output using a transformation function.
425 ///
426 /// Consumes self and returns a new supplier that applies the
427 /// mapper to each output.
428 ///
429 /// # Parameters
430 ///
431 /// * `mapper` - The function to apply to the output
432 ///
433 /// # Returns
434 ///
435 /// A new mapped `BoxSupplier<U>`
436 ///
437 /// # Examples
438 ///
439 /// ```rust
440 /// use prism3_function::{BoxSupplier, Supplier};
441 ///
442 /// let mut mapped = BoxSupplier::new(|| 10)
443 /// .map(|x| x * 2)
444 /// .map(|x| x + 5);
445 /// assert_eq!(mapped.get(), 25);
446 /// ```
447 pub fn map<U, F>(mut self, mut mapper: F) -> BoxSupplier<U>
448 where
449 F: FnMut(T) -> U + 'static,
450 U: 'static,
451 {
452 BoxSupplier::new(move || mapper(self.get()))
453 }
454
455 /// Filters output based on a predicate.
456 ///
457 /// Returns a new supplier that returns `Some(value)` if the
458 /// predicate is satisfied, `None` otherwise.
459 ///
460 /// # Parameters
461 ///
462 /// * `predicate` - The predicate to test the supplied value
463 ///
464 /// # Returns
465 ///
466 /// A new filtered `BoxSupplier<Option<T>>`
467 ///
468 /// # Examples
469 ///
470 /// ```rust
471 /// use prism3_function::{BoxSupplier, Supplier};
472 ///
473 /// let mut counter = 0;
474 /// let mut filtered = BoxSupplier::new(move || {
475 /// counter += 1;
476 /// counter
477 /// }).filter(|x| x % 2 == 0);
478 ///
479 /// assert_eq!(filtered.get(), None); // 1 is odd
480 /// assert_eq!(filtered.get(), Some(2)); // 2 is even
481 /// ```
482 pub fn filter<P>(mut self, mut predicate: P) -> BoxSupplier<Option<T>>
483 where
484 P: FnMut(&T) -> bool + 'static,
485 {
486 BoxSupplier::new(move || {
487 let value = self.get();
488 if predicate(&value) {
489 Some(value)
490 } else {
491 None
492 }
493 })
494 }
495
496 /// Combines this supplier with another, producing a tuple.
497 ///
498 /// Consumes both suppliers and returns a new supplier that
499 /// produces `(T, U)` tuples.
500 ///
501 /// # Parameters
502 ///
503 /// * `other` - The other supplier to combine with
504 ///
505 /// # Returns
506 ///
507 /// A new `BoxSupplier<(T, U)>`
508 ///
509 /// # Examples
510 ///
511 /// ```rust
512 /// use prism3_function::{BoxSupplier, Supplier};
513 ///
514 /// let first = BoxSupplier::new(|| 42);
515 /// let second = BoxSupplier::new(|| "hello");
516 /// let mut zipped = first.zip(second);
517 ///
518 /// assert_eq!(zipped.get(), (42, "hello"));
519 /// ```
520 pub fn zip<U>(mut self, mut other: BoxSupplier<U>) -> BoxSupplier<(T, U)>
521 where
522 U: 'static,
523 {
524 BoxSupplier::new(move || (self.get(), other.get()))
525 }
526
527 /// Creates a memoizing supplier.
528 ///
529 /// Returns a new supplier that caches the first value it
530 /// produces. All subsequent calls return the cached value.
531 ///
532 /// # Returns
533 ///
534 /// A new memoized `BoxSupplier<T>`
535 ///
536 /// # Examples
537 ///
538 /// ```rust
539 /// use prism3_function::{BoxSupplier, Supplier};
540 ///
541 /// let mut call_count = 0;
542 /// let mut memoized = BoxSupplier::new(move || {
543 /// call_count += 1;
544 /// 42
545 /// }).memoize();
546 ///
547 /// assert_eq!(memoized.get(), 42); // Calls underlying function
548 /// assert_eq!(memoized.get(), 42); // Returns cached value
549 /// ```
550 pub fn memoize(mut self) -> BoxSupplier<T>
551 where
552 T: Clone + 'static,
553 {
554 let mut cache: Option<T> = None;
555 BoxSupplier::new(move || {
556 if let Some(ref cached) = cache {
557 cached.clone()
558 } else {
559 let value = self.get();
560 cache = Some(value.clone());
561 value
562 }
563 })
564 }
565}
566
567impl<T> Supplier<T> for BoxSupplier<T> {
568 fn get(&mut self) -> T {
569 (self.function)()
570 }
571
572 fn into_box(self) -> BoxSupplier<T>
573 where
574 T: 'static,
575 {
576 self
577 }
578
579 fn into_rc(self) -> RcSupplier<T>
580 where
581 T: 'static,
582 {
583 RcSupplier::new(self.function)
584 }
585
586 fn into_arc(self) -> ArcSupplier<T>
587 where
588 T: Send + 'static,
589 {
590 // Note: This conversion may fail if the inner function is
591 // not Send. We panic here to indicate the error at runtime.
592 panic!(
593 "Cannot convert BoxSupplier to ArcSupplier: inner \
594 function may not be Send. Create ArcSupplier directly \
595 with Send closures."
596 )
597 }
598}
599
600// ==========================================================================
601// ArcSupplier - Thread-safe Shared Ownership Implementation
602// ==========================================================================
603
604/// Thread-safe shared ownership supplier.
605///
606/// Uses `Arc<Mutex<dyn FnMut() -> T + Send>>` for thread-safe
607/// shared ownership. Can be cloned and sent across threads.
608///
609/// # Ownership Model
610///
611/// Methods borrow `&self` instead of consuming `self`. The original
612/// supplier remains usable after method calls:
613///
614/// ```rust
615/// use prism3_function::{ArcSupplier, Supplier};
616///
617/// let source = ArcSupplier::new(|| 10);
618/// let mapped = source.map(|x| x * 2);
619/// // source is still usable here!
620/// ```
621///
622/// # Examples
623///
624/// ## Thread-safe Counter
625///
626/// ```rust
627/// use prism3_function::{ArcSupplier, Supplier};
628/// use std::sync::{Arc, Mutex};
629/// use std::thread;
630///
631/// let counter = Arc::new(Mutex::new(0));
632/// let counter_clone = Arc::clone(&counter);
633///
634/// let supplier = ArcSupplier::new(move || {
635/// let mut c = counter_clone.lock().unwrap();
636/// *c += 1;
637/// *c
638/// });
639///
640/// let mut s1 = supplier.clone();
641/// let mut s2 = supplier.clone();
642///
643/// let h1 = thread::spawn(move || s1.get());
644/// let h2 = thread::spawn(move || s2.get());
645///
646/// let v1 = h1.join().unwrap();
647/// let v2 = h2.join().unwrap();
648/// assert!(v1 != v2);
649/// ```
650///
651/// ## Reusable Transformations
652///
653/// ```rust
654/// use prism3_function::{ArcSupplier, Supplier};
655///
656/// let base = ArcSupplier::new(|| 10);
657/// let doubled = base.map(|x| x * 2);
658/// let tripled = base.map(|x| x * 3);
659///
660/// // All remain usable
661/// let mut b = base;
662/// let mut d = doubled;
663/// let mut t = tripled;
664/// assert_eq!(b.get(), 10);
665/// assert_eq!(d.get(), 20);
666/// assert_eq!(t.get(), 30);
667/// ```
668///
669/// # Author
670///
671/// Haixing Hu
672pub struct ArcSupplier<T> {
673 function: Arc<Mutex<dyn FnMut() -> T + Send>>,
674}
675
676impl<T> ArcSupplier<T>
677where
678 T: Send + 'static,
679{
680 /// Creates a new `ArcSupplier`.
681 ///
682 /// # Parameters
683 ///
684 /// * `f` - The closure to wrap
685 ///
686 /// # Returns
687 ///
688 /// A new `ArcSupplier<T>` instance
689 ///
690 /// # Examples
691 ///
692 /// ```rust
693 /// use prism3_function::{ArcSupplier, Supplier};
694 ///
695 /// let supplier = ArcSupplier::new(|| 42);
696 /// let mut s = supplier;
697 /// assert_eq!(s.get(), 42);
698 /// ```
699 pub fn new<F>(f: F) -> Self
700 where
701 F: FnMut() -> T + Send + 'static,
702 {
703 ArcSupplier {
704 function: Arc::new(Mutex::new(f)),
705 }
706 }
707
708 /// Creates a constant supplier.
709 ///
710 /// # Parameters
711 ///
712 /// * `value` - The constant value to return
713 ///
714 /// # Returns
715 ///
716 /// A constant supplier
717 ///
718 /// # Examples
719 ///
720 /// ```rust
721 /// use prism3_function::{ArcSupplier, Supplier};
722 ///
723 /// let constant = ArcSupplier::constant(42);
724 /// let mut s = constant;
725 /// assert_eq!(s.get(), 42);
726 /// assert_eq!(s.get(), 42);
727 /// ```
728 pub fn constant(value: T) -> Self
729 where
730 T: Clone + 'static,
731 {
732 ArcSupplier::new(move || value.clone())
733 }
734
735 /// Maps the output using a transformation function.
736 ///
737 /// Borrows `&self`, doesn't consume the original supplier.
738 ///
739 /// # Parameters
740 ///
741 /// * `mapper` - The function to apply to the output
742 ///
743 /// # Returns
744 ///
745 /// A new mapped `ArcSupplier<U>`
746 ///
747 /// # Examples
748 ///
749 /// ```rust
750 /// use prism3_function::{ArcSupplier, Supplier};
751 ///
752 /// let source = ArcSupplier::new(|| 10);
753 /// let mapped = source.map(|x| x * 2);
754 /// // source is still usable
755 /// let mut s = mapped;
756 /// assert_eq!(s.get(), 20);
757 /// ```
758 pub fn map<U, F>(&self, mapper: F) -> ArcSupplier<U>
759 where
760 F: FnMut(T) -> U + Send + 'static,
761 U: Send + 'static,
762 {
763 let self_fn = Arc::clone(&self.function);
764 let mapper = Arc::new(Mutex::new(mapper));
765 ArcSupplier {
766 function: Arc::new(Mutex::new(move || {
767 let value = self_fn.lock().unwrap()();
768 mapper.lock().unwrap()(value)
769 })),
770 }
771 }
772
773 /// Filters output based on a predicate.
774 ///
775 /// # Parameters
776 ///
777 /// * `predicate` - The predicate to test the supplied value
778 ///
779 /// # Returns
780 ///
781 /// A new filtered `ArcSupplier<Option<T>>`
782 ///
783 /// # Examples
784 ///
785 /// ```rust
786 /// use prism3_function::{ArcSupplier, Supplier};
787 /// use std::sync::{Arc, Mutex};
788 ///
789 /// let counter = Arc::new(Mutex::new(0));
790 /// let counter_clone = Arc::clone(&counter);
791 /// let source = ArcSupplier::new(move || {
792 /// let mut c = counter_clone.lock().unwrap();
793 /// *c += 1;
794 /// *c
795 /// });
796 /// let filtered = source.filter(|x| x % 2 == 0);
797 ///
798 /// let mut s = filtered;
799 /// assert_eq!(s.get(), None); // 1 is odd
800 /// assert_eq!(s.get(), Some(2)); // 2 is even
801 /// ```
802 pub fn filter<P>(&self, predicate: P) -> ArcSupplier<Option<T>>
803 where
804 P: FnMut(&T) -> bool + Send + 'static,
805 {
806 let self_fn = Arc::clone(&self.function);
807 let predicate = Arc::new(Mutex::new(predicate));
808 ArcSupplier {
809 function: Arc::new(Mutex::new(move || {
810 let value = self_fn.lock().unwrap()();
811 if predicate.lock().unwrap()(&value) {
812 Some(value)
813 } else {
814 None
815 }
816 })),
817 }
818 }
819
820 /// Combines this supplier with another, producing a tuple.
821 ///
822 /// # Parameters
823 ///
824 /// * `other` - The other supplier to combine with. **Note: This parameter
825 /// is passed by reference, so the original supplier remains usable.**
826 /// Can be:
827 /// - An `ArcSupplier<U>` (passed by reference)
828 /// - Any type implementing `Supplier<U> + Send`
829 ///
830 /// # Returns
831 ///
832 /// A new `ArcSupplier<(T, U)>`
833 ///
834 /// # Examples
835 ///
836 /// ```rust
837 /// use prism3_function::{ArcSupplier, Supplier};
838 ///
839 /// let first = ArcSupplier::new(|| 42);
840 /// let second = ArcSupplier::new(|| "hello");
841 ///
842 /// // second is passed by reference, so it remains usable
843 /// let zipped = first.zip(&second);
844 ///
845 /// let mut z = zipped;
846 /// assert_eq!(z.get(), (42, "hello"));
847 ///
848 /// // Both first and second still usable
849 /// let mut f = first;
850 /// let mut s = second;
851 /// assert_eq!(f.get(), 42);
852 /// assert_eq!(s.get(), "hello");
853 /// ```
854 pub fn zip<U>(&self, other: &ArcSupplier<U>) -> ArcSupplier<(T, U)>
855 where
856 U: Send + 'static,
857 {
858 let first = Arc::clone(&self.function);
859 let second = Arc::clone(&other.function);
860 ArcSupplier {
861 function: Arc::new(Mutex::new(move || {
862 (first.lock().unwrap()(), second.lock().unwrap()())
863 })),
864 }
865 }
866
867 /// Creates a memoizing supplier.
868 ///
869 /// # Returns
870 ///
871 /// A new memoized `ArcSupplier<T>`
872 ///
873 /// # Examples
874 ///
875 /// ```rust
876 /// use prism3_function::{ArcSupplier, Supplier};
877 /// use std::sync::{Arc, Mutex};
878 ///
879 /// let call_count = Arc::new(Mutex::new(0));
880 /// let call_count_clone = Arc::clone(&call_count);
881 /// let source = ArcSupplier::new(move || {
882 /// let mut c = call_count_clone.lock().unwrap();
883 /// *c += 1;
884 /// 42
885 /// });
886 /// let memoized = source.memoize();
887 ///
888 /// let mut s = memoized;
889 /// assert_eq!(s.get(), 42); // Calls underlying function
890 /// assert_eq!(s.get(), 42); // Returns cached value
891 /// assert_eq!(*call_count.lock().unwrap(), 1);
892 /// ```
893 pub fn memoize(&self) -> ArcSupplier<T>
894 where
895 T: Clone + 'static,
896 {
897 let self_fn = Arc::clone(&self.function);
898 let cache: Arc<Mutex<Option<T>>> = Arc::new(Mutex::new(None));
899 ArcSupplier {
900 function: Arc::new(Mutex::new(move || {
901 let mut cache_guard = cache.lock().unwrap();
902 if let Some(ref cached) = *cache_guard {
903 cached.clone()
904 } else {
905 let value = self_fn.lock().unwrap()();
906 *cache_guard = Some(value.clone());
907 value
908 }
909 })),
910 }
911 }
912}
913
914impl<T> Supplier<T> for ArcSupplier<T> {
915 fn get(&mut self) -> T {
916 (self.function.lock().unwrap())()
917 }
918
919 fn into_box(self) -> BoxSupplier<T>
920 where
921 T: 'static,
922 {
923 let self_fn = self.function;
924 BoxSupplier::new(move || self_fn.lock().unwrap()())
925 }
926
927 fn into_rc(self) -> RcSupplier<T>
928 where
929 T: 'static,
930 {
931 let self_fn = self.function;
932 RcSupplier::new(move || self_fn.lock().unwrap()())
933 }
934
935 fn into_arc(self) -> ArcSupplier<T>
936 where
937 T: Send + 'static,
938 {
939 self
940 }
941}
942
943impl<T> Clone for ArcSupplier<T> {
944 /// Clones the `ArcSupplier`.
945 ///
946 /// Creates a new instance that shares the underlying function
947 /// with the original.
948 fn clone(&self) -> Self {
949 Self {
950 function: Arc::clone(&self.function),
951 }
952 }
953}
954
955// ==========================================================================
956// RcSupplier - Single-threaded Shared Ownership Implementation
957// ==========================================================================
958
959/// Single-threaded shared ownership supplier.
960///
961/// Uses `Rc<RefCell<dyn FnMut() -> T>>` for single-threaded shared
962/// ownership. Can be cloned but not sent across threads.
963///
964/// # Ownership Model
965///
966/// Like `ArcSupplier`, methods borrow `&self` instead of consuming
967/// `self`:
968///
969/// ```rust
970/// use prism3_function::{RcSupplier, Supplier};
971///
972/// let source = RcSupplier::new(|| 10);
973/// let mapped = source.map(|x| x * 2);
974/// // source is still usable here!
975/// ```
976///
977/// # Examples
978///
979/// ## Shared Counter
980///
981/// ```rust
982/// use prism3_function::{RcSupplier, Supplier};
983/// use std::rc::Rc;
984/// use std::cell::RefCell;
985///
986/// let counter = Rc::new(RefCell::new(0));
987/// let counter_clone = Rc::clone(&counter);
988///
989/// let supplier = RcSupplier::new(move || {
990/// let mut c = counter_clone.borrow_mut();
991/// *c += 1;
992/// *c
993/// });
994///
995/// let mut s1 = supplier.clone();
996/// let mut s2 = supplier.clone();
997/// assert_eq!(s1.get(), 1);
998/// assert_eq!(s2.get(), 2);
999/// ```
1000///
1001/// ## Reusable Transformations
1002///
1003/// ```rust
1004/// use prism3_function::{RcSupplier, Supplier};
1005///
1006/// let base = RcSupplier::new(|| 10);
1007/// let doubled = base.map(|x| x * 2);
1008/// let tripled = base.map(|x| x * 3);
1009///
1010/// let mut b = base;
1011/// let mut d = doubled;
1012/// let mut t = tripled;
1013/// assert_eq!(b.get(), 10);
1014/// assert_eq!(d.get(), 20);
1015/// assert_eq!(t.get(), 30);
1016/// ```
1017///
1018/// # Author
1019///
1020/// Haixing Hu
1021pub struct RcSupplier<T> {
1022 function: Rc<RefCell<dyn FnMut() -> T>>,
1023}
1024
1025impl<T> RcSupplier<T>
1026where
1027 T: 'static,
1028{
1029 /// Creates a new `RcSupplier`.
1030 ///
1031 /// # Parameters
1032 ///
1033 /// * `f` - The closure to wrap
1034 ///
1035 /// # Returns
1036 ///
1037 /// A new `RcSupplier<T>` instance
1038 ///
1039 /// # Examples
1040 ///
1041 /// ```rust
1042 /// use prism3_function::{RcSupplier, Supplier};
1043 ///
1044 /// let supplier = RcSupplier::new(|| 42);
1045 /// let mut s = supplier;
1046 /// assert_eq!(s.get(), 42);
1047 /// ```
1048 pub fn new<F>(f: F) -> Self
1049 where
1050 F: FnMut() -> T + 'static,
1051 {
1052 RcSupplier {
1053 function: Rc::new(RefCell::new(f)),
1054 }
1055 }
1056
1057 /// Creates a constant supplier.
1058 ///
1059 /// # Parameters
1060 ///
1061 /// * `value` - The constant value to return
1062 ///
1063 /// # Returns
1064 ///
1065 /// A constant supplier
1066 ///
1067 /// # Examples
1068 ///
1069 /// ```rust
1070 /// use prism3_function::{RcSupplier, Supplier};
1071 ///
1072 /// let constant = RcSupplier::constant(42);
1073 /// let mut s = constant;
1074 /// assert_eq!(s.get(), 42);
1075 /// assert_eq!(s.get(), 42);
1076 /// ```
1077 pub fn constant(value: T) -> Self
1078 where
1079 T: Clone + 'static,
1080 {
1081 RcSupplier::new(move || value.clone())
1082 }
1083
1084 /// Maps the output using a transformation function.
1085 ///
1086 /// Borrows `&self`, doesn't consume the original supplier.
1087 ///
1088 /// # Parameters
1089 ///
1090 /// * `mapper` - The function to apply to the output
1091 ///
1092 /// # Returns
1093 ///
1094 /// A new mapped `RcSupplier<U>`
1095 ///
1096 /// # Examples
1097 ///
1098 /// ```rust
1099 /// use prism3_function::{RcSupplier, Supplier};
1100 ///
1101 /// let source = RcSupplier::new(|| 10);
1102 /// let mapped = source.map(|x| x * 2);
1103 /// // source is still usable
1104 /// let mut s = mapped;
1105 /// assert_eq!(s.get(), 20);
1106 /// ```
1107 pub fn map<U, F>(&self, mapper: F) -> RcSupplier<U>
1108 where
1109 F: FnMut(T) -> U + 'static,
1110 U: 'static,
1111 {
1112 let self_fn = Rc::clone(&self.function);
1113 let mapper = Rc::new(RefCell::new(mapper));
1114 RcSupplier {
1115 function: Rc::new(RefCell::new(move || {
1116 let value = self_fn.borrow_mut()();
1117 mapper.borrow_mut()(value)
1118 })),
1119 }
1120 }
1121
1122 /// Filters output based on a predicate.
1123 ///
1124 /// # Parameters
1125 ///
1126 /// * `predicate` - The predicate to test the supplied value
1127 ///
1128 /// # Returns
1129 ///
1130 /// A new filtered `RcSupplier<Option<T>>`
1131 ///
1132 /// # Examples
1133 ///
1134 /// ```rust
1135 /// use prism3_function::{RcSupplier, Supplier};
1136 /// use std::rc::Rc;
1137 /// use std::cell::RefCell;
1138 ///
1139 /// let counter = Rc::new(RefCell::new(0));
1140 /// let counter_clone = Rc::clone(&counter);
1141 /// let source = RcSupplier::new(move || {
1142 /// let mut c = counter_clone.borrow_mut();
1143 /// *c += 1;
1144 /// *c
1145 /// });
1146 /// let filtered = source.filter(|x| x % 2 == 0);
1147 ///
1148 /// let mut s = filtered;
1149 /// assert_eq!(s.get(), None); // 1 is odd
1150 /// assert_eq!(s.get(), Some(2)); // 2 is even
1151 /// ```
1152 pub fn filter<P>(&self, predicate: P) -> RcSupplier<Option<T>>
1153 where
1154 P: FnMut(&T) -> bool + 'static,
1155 {
1156 let self_fn = Rc::clone(&self.function);
1157 let predicate = Rc::new(RefCell::new(predicate));
1158 RcSupplier {
1159 function: Rc::new(RefCell::new(move || {
1160 let value = self_fn.borrow_mut()();
1161 if predicate.borrow_mut()(&value) {
1162 Some(value)
1163 } else {
1164 None
1165 }
1166 })),
1167 }
1168 }
1169
1170 /// Combines this supplier with another, producing a tuple.
1171 ///
1172 /// # Parameters
1173 ///
1174 /// * `other` - The other supplier to combine with. **Note: This parameter
1175 /// is passed by reference, so the original supplier remains usable.**
1176 /// Can be:
1177 /// - An `RcSupplier<U>` (passed by reference)
1178 /// - Any type implementing `Supplier<U>`
1179 ///
1180 /// # Returns
1181 ///
1182 /// A new `RcSupplier<(T, U)>`
1183 ///
1184 /// # Examples
1185 ///
1186 /// ```rust
1187 /// use prism3_function::{RcSupplier, Supplier};
1188 ///
1189 /// let first = RcSupplier::new(|| 42);
1190 /// let second = RcSupplier::new(|| "hello");
1191 ///
1192 /// // second is passed by reference, so it remains usable
1193 /// let zipped = first.zip(&second);
1194 ///
1195 /// let mut z = zipped;
1196 /// assert_eq!(z.get(), (42, "hello"));
1197 ///
1198 /// // Both first and second still usable
1199 /// let mut f = first;
1200 /// let mut s = second;
1201 /// assert_eq!(f.get(), 42);
1202 /// assert_eq!(s.get(), "hello");
1203 /// ```
1204 pub fn zip<U>(&self, other: &RcSupplier<U>) -> RcSupplier<(T, U)>
1205 where
1206 U: 'static,
1207 {
1208 let first = Rc::clone(&self.function);
1209 let second = Rc::clone(&other.function);
1210 RcSupplier {
1211 function: Rc::new(RefCell::new(move || {
1212 (first.borrow_mut()(), second.borrow_mut()())
1213 })),
1214 }
1215 }
1216
1217 /// Creates a memoizing supplier.
1218 ///
1219 /// # Returns
1220 ///
1221 /// A new memoized `RcSupplier<T>`
1222 ///
1223 /// # Examples
1224 ///
1225 /// ```rust
1226 /// use prism3_function::{RcSupplier, Supplier};
1227 /// use std::rc::Rc;
1228 /// use std::cell::RefCell;
1229 ///
1230 /// let call_count = Rc::new(RefCell::new(0));
1231 /// let call_count_clone = Rc::clone(&call_count);
1232 /// let source = RcSupplier::new(move || {
1233 /// let mut c = call_count_clone.borrow_mut();
1234 /// *c += 1;
1235 /// 42
1236 /// });
1237 /// let memoized = source.memoize();
1238 ///
1239 /// let mut s = memoized;
1240 /// assert_eq!(s.get(), 42); // Calls underlying function
1241 /// assert_eq!(s.get(), 42); // Returns cached value
1242 /// assert_eq!(*call_count.borrow(), 1);
1243 /// ```
1244 pub fn memoize(&self) -> RcSupplier<T>
1245 where
1246 T: Clone + 'static,
1247 {
1248 let self_fn = Rc::clone(&self.function);
1249 let cache: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
1250 RcSupplier {
1251 function: Rc::new(RefCell::new(move || {
1252 let mut cache_ref = cache.borrow_mut();
1253 if let Some(ref cached) = *cache_ref {
1254 cached.clone()
1255 } else {
1256 let value = self_fn.borrow_mut()();
1257 *cache_ref = Some(value.clone());
1258 value
1259 }
1260 })),
1261 }
1262 }
1263}
1264
1265impl<T> Supplier<T> for RcSupplier<T> {
1266 fn get(&mut self) -> T {
1267 (self.function.borrow_mut())()
1268 }
1269
1270 fn into_box(self) -> BoxSupplier<T>
1271 where
1272 T: 'static,
1273 {
1274 let self_fn = self.function;
1275 BoxSupplier::new(move || self_fn.borrow_mut()())
1276 }
1277
1278 fn into_rc(self) -> RcSupplier<T>
1279 where
1280 T: 'static,
1281 {
1282 self
1283 }
1284
1285 fn into_arc(self) -> ArcSupplier<T>
1286 where
1287 T: Send + 'static,
1288 {
1289 panic!("Cannot convert RcSupplier to ArcSupplier (not Send)")
1290 }
1291}
1292
1293impl<T> Clone for RcSupplier<T> {
1294 /// Clones the `RcSupplier`.
1295 ///
1296 /// Creates a new instance that shares the underlying function
1297 /// with the original.
1298 fn clone(&self) -> Self {
1299 Self {
1300 function: Rc::clone(&self.function),
1301 }
1302 }
1303}