Expand description
§Supplier Types
Provides supplier implementations that generate and return values without taking any input parameters.
§Overview
A Supplier is a functional abstraction that generates and provides a value without accepting input. It can produce new values each time (like a factory) or return fixed values (like constants).
This module implements Approach 3 from the design document: a
unified Supplier trait with multiple concrete implementations
optimized for different ownership and concurrency scenarios.
§Core Design Principles
- Returns Ownership:
SupplierreturnsT(not&T) to avoid lifetime issues - Uses
&mut self: Typical scenarios (counters, generators) require state modification - No ReadonlySupplier: Main use cases require state modification; value is extremely low
§Three Implementations
-
BoxSupplier<T>: Single ownership usingBox<dyn FnMut() -> T>. Zero overhead, cannot be cloned. Best for one-time use and builder patterns. -
ArcSupplier<T>: Thread-safe shared ownership usingArc<Mutex<dyn FnMut() -> T + Send>>. Can be cloned and sent across threads. Higher overhead due to locking. -
RcSupplier<T>: Single-threaded shared ownership usingRc<RefCell<dyn FnMut() -> T>>. Can be cloned but not sent across threads. Lower overhead thanArcSupplier.
§Comparison with Other Functional Abstractions
| Type | Input | Output | self | Modifies? | Use Case |
|---|---|---|---|---|---|
| Supplier | None | T | &mut | Yes | Factory |
| Consumer | &T | () | &mut | Yes | Observer |
| Predicate | &T | bool | &self | No | Filter |
| Function | &T | R | &self | No | Transform |
§Examples
§Basic Counter
use prism3_function::{BoxSupplier, Supplier};
let mut counter = 0;
let mut supplier = BoxSupplier::new(move || {
counter += 1;
counter
});
assert_eq!(supplier.get(), 1);
assert_eq!(supplier.get(), 2);
assert_eq!(supplier.get(), 3);§Method Chaining
use prism3_function::{BoxSupplier, Supplier};
let mut pipeline = BoxSupplier::new(|| 10)
.map(|x| x * 2)
.map(|x| x + 5);
assert_eq!(pipeline.get(), 25);§Thread-safe Sharing
use prism3_function::{ArcSupplier, Supplier};
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let counter_clone = Arc::clone(&counter);
let supplier = ArcSupplier::new(move || {
let mut c = counter_clone.lock().unwrap();
*c += 1;
*c
});
let mut s1 = supplier.clone();
let mut s2 = supplier.clone();
let h1 = thread::spawn(move || s1.get());
let h2 = thread::spawn(move || s2.get());
let v1 = h1.join().unwrap();
let v2 = h2.join().unwrap();
assert!(v1 != v2);
assert_eq!(*counter.lock().unwrap(), 2);§Author
Haixing Hu
Structs§
- ArcSupplier
- Thread-safe shared ownership supplier.
- BoxSupplier
- Box-based single ownership supplier.
- RcSupplier
- Single-threaded shared ownership supplier.
Traits§
- Supplier
- Supplier trait: generates and returns values without input.