ArcSupplier

Struct ArcSupplier 

Source
pub struct ArcSupplier<T> { /* private fields */ }
Expand description

Thread-safe shared ownership supplier.

Uses Arc<Mutex<dyn FnMut() -> T + Send>> for thread-safe shared ownership. Can be cloned and sent across threads.

§Ownership Model

Methods borrow &self instead of consuming self. The original supplier remains usable after method calls:

use prism3_function::{ArcSupplier, Supplier};

let source = ArcSupplier::new(|| 10);
let mapped = source.map(|x| x * 2);
// source is still usable here!

§Examples

§Thread-safe Counter

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);

§Reusable Transformations

use prism3_function::{ArcSupplier, Supplier};

let base = ArcSupplier::new(|| 10);
let doubled = base.map(|x| x * 2);
let tripled = base.map(|x| x * 3);

// All remain usable
let mut b = base;
let mut d = doubled;
let mut t = tripled;
assert_eq!(b.get(), 10);
assert_eq!(d.get(), 20);
assert_eq!(t.get(), 30);

§Author

Haixing Hu

Implementations§

Source§

impl<T> ArcSupplier<T>
where T: Send + 'static,

Source

pub fn new<F>(f: F) -> Self
where F: FnMut() -> T + Send + 'static,

Creates a new ArcSupplier.

§Parameters
  • f - The closure to wrap
§Returns

A new ArcSupplier<T> instance

§Examples
use prism3_function::{ArcSupplier, Supplier};

let supplier = ArcSupplier::new(|| 42);
let mut s = supplier;
assert_eq!(s.get(), 42);
Examples found in repository?
examples/supplier_demo.rs (line 135)
131fn demo_arc_supplier() {
132    println!("--- ArcSupplier ---");
133
134    // Basic usage
135    let supplier = ArcSupplier::new(|| 42);
136    let mut s = supplier;
137    println!("Basic: {}", s.get());
138
139    // Reusable transformations
140    let source = ArcSupplier::new(|| 10);
141    let doubled = source.map(|x| x * 2);
142    let tripled = source.map(|x| x * 3);
143
144    let mut s = source;
145    let mut d = doubled;
146    let mut t = tripled;
147    println!("Source: {}", s.get());
148    println!("Doubled: {}", d.get());
149    println!("Tripled: {}", t.get());
150
151    // Memoization
152    let call_count = Arc::new(Mutex::new(0));
153    let call_count_clone = Arc::clone(&call_count);
154    let source = ArcSupplier::new(move || {
155        let mut c = call_count_clone.lock().unwrap();
156        *c += 1;
157        println!("  Computation #{}", *c);
158        42
159    });
160    let memoized = source.memoize();
161
162    let mut m = memoized;
163    println!("First call: {}", m.get());
164    println!("Second call (cached): {}", m.get());
165    println!();
166}
167
168fn demo_arc_supplier_threading() {
169    println!("--- ArcSupplier Threading ---");
170
171    let counter = Arc::new(Mutex::new(0));
172    let counter_clone = Arc::clone(&counter);
173
174    let supplier = ArcSupplier::new(move || {
175        let mut c = counter_clone.lock().unwrap();
176        *c += 1;
177        *c
178    });
179
180    let mut s1 = supplier.clone();
181    let mut s2 = supplier.clone();
182    let mut s3 = supplier;
183
184    let h1 = thread::spawn(move || {
185        let v1 = s1.get();
186        let v2 = s1.get();
187        println!("Thread 1: {} {}", v1, v2);
188        (v1, v2)
189    });
190
191    let h2 = thread::spawn(move || {
192        let v1 = s2.get();
193        let v2 = s2.get();
194        println!("Thread 2: {} {}", v1, v2);
195        (v1, v2)
196    });
197
198    let v1 = s3.get();
199    let v2 = s3.get();
200    println!("Main thread: {} {}", v1, v2);
201
202    h1.join().unwrap();
203    h2.join().unwrap();
204
205    println!("Final counter: {}", *counter.lock().unwrap());
206    println!();
207}
208
209fn demo_rc_supplier() {
210    println!("--- RcSupplier ---");
211
212    // Basic usage
213    let supplier = RcSupplier::new(|| 42);
214    let mut s = supplier;
215    println!("Basic: {}", s.get());
216
217    // Shared state
218    let counter = Rc::new(RefCell::new(0));
219    let counter_clone = Rc::clone(&counter);
220    let supplier = RcSupplier::new(move || {
221        let mut c = counter_clone.borrow_mut();
222        *c += 1;
223        *c
224    });
225
226    let mut s1 = supplier.clone();
227    let mut s2 = supplier.clone();
228
229    println!("First clone: {}", s1.get());
230    println!("Second clone: {}", s2.get());
231    println!("First clone again: {}", s1.get());
232
233    // Reusable transformations
234    let source = RcSupplier::new(|| 10);
235    let doubled = source.map(|x| x * 2);
236    let tripled = source.map(|x| x * 3);
237    let squared = source.map(|x| x * x);
238
239    let mut s = source;
240    let mut d = doubled;
241    let mut t = tripled;
242    let mut sq = squared;
243
244    println!("Source: {}", s.get());
245    println!("Doubled: {}", d.get());
246    println!("Tripled: {}", t.get());
247    println!("Squared: {}", sq.get());
248    println!();
249}
250
251fn demo_type_conversions() {
252    println!("--- Type Conversions ---");
253
254    // Closure to Box
255    let closure = || 42;
256    let mut boxed = Supplier::into_box(closure);
257    println!("Closure -> Box: {}", boxed.get());
258
259    // Closure to Rc
260    let closure = || 100;
261    let mut rc = closure.into_rc();
262    println!("Closure -> Rc: {}", rc.get());
263
264    // Closure to Arc
265    let closure = || 200;
266    let mut arc = closure.into_arc();
267    println!("Closure -> Arc: {}", arc.get());
268
269    // Box to Rc
270    let boxed = BoxSupplier::new(|| 42);
271    let mut rc = boxed.into_rc();
272    println!("Box -> Rc: {}", rc.get());
273
274    // Arc to Box
275    let arc = ArcSupplier::new(|| 42);
276    let mut boxed = arc.into_box();
277    println!("Arc -> Box: {}", boxed.get());
278
279    // Rc to Box
280    let rc = RcSupplier::new(|| 42);
281    let mut boxed = rc.into_box();
282    println!("Rc -> Box: {}", boxed.get());
283
284    println!();
285}
Source

pub fn constant(value: T) -> Self
where T: Clone + 'static,

Creates a constant supplier.

§Parameters
  • value - The constant value to return
§Returns

A constant supplier

§Examples
use prism3_function::{ArcSupplier, Supplier};

let constant = ArcSupplier::constant(42);
let mut s = constant;
assert_eq!(s.get(), 42);
assert_eq!(s.get(), 42);
Source

pub fn map<U, F>(&self, mapper: F) -> ArcSupplier<U>
where F: Mapper<T, U> + Send + 'static, U: Send + 'static,

Maps the output using a transformation function.

Borrows &self, doesn’t consume the original supplier.

§Parameters
  • mapper - The mapper to apply to the output. Can be:
    • A closure: |x: T| -> U (must be Send)
    • A function pointer: fn(T) -> U
    • A BoxMapper<T, U>, RcMapper<T, U>, ArcMapper<T, U>
    • Any type implementing Mapper<T, U> + Send
§Returns

A new mapped ArcSupplier<U>

§Examples
§Using with closure
use prism3_function::{ArcSupplier, Supplier};

let source = ArcSupplier::new(|| 10);
let mapped = source.map(|x| x * 2);
// source is still usable
let mut s = mapped;
assert_eq!(s.get(), 20);
§Using with Mapper object
use prism3_function::{ArcSupplier, ArcMapper, Supplier, Mapper};

let mapper = ArcMapper::new(|x: i32| x * 2);
let source = ArcSupplier::new(|| 10);
let mut supplier = source.map(mapper);
assert_eq!(supplier.get(), 20);
Examples found in repository?
examples/supplier_demo.rs (line 141)
131fn demo_arc_supplier() {
132    println!("--- ArcSupplier ---");
133
134    // Basic usage
135    let supplier = ArcSupplier::new(|| 42);
136    let mut s = supplier;
137    println!("Basic: {}", s.get());
138
139    // Reusable transformations
140    let source = ArcSupplier::new(|| 10);
141    let doubled = source.map(|x| x * 2);
142    let tripled = source.map(|x| x * 3);
143
144    let mut s = source;
145    let mut d = doubled;
146    let mut t = tripled;
147    println!("Source: {}", s.get());
148    println!("Doubled: {}", d.get());
149    println!("Tripled: {}", t.get());
150
151    // Memoization
152    let call_count = Arc::new(Mutex::new(0));
153    let call_count_clone = Arc::clone(&call_count);
154    let source = ArcSupplier::new(move || {
155        let mut c = call_count_clone.lock().unwrap();
156        *c += 1;
157        println!("  Computation #{}", *c);
158        42
159    });
160    let memoized = source.memoize();
161
162    let mut m = memoized;
163    println!("First call: {}", m.get());
164    println!("Second call (cached): {}", m.get());
165    println!();
166}
Source

pub fn filter<P>(&self, predicate: P) -> ArcSupplier<Option<T>>
where P: FnMut(&T) -> bool + Send + 'static,

Filters output based on a predicate.

§Parameters
  • predicate - The predicate to test the supplied value
§Returns

A new filtered ArcSupplier<Option<T>>

§Examples
use prism3_function::{ArcSupplier, Supplier};
use std::sync::{Arc, Mutex};

let counter = Arc::new(Mutex::new(0));
let counter_clone = Arc::clone(&counter);
let source = ArcSupplier::new(move || {
    let mut c = counter_clone.lock().unwrap();
    *c += 1;
    *c
});
let filtered = source.filter(|x| x % 2 == 0);

let mut s = filtered;
assert_eq!(s.get(), None);     // 1 is odd
assert_eq!(s.get(), Some(2));  // 2 is even
Source

pub fn zip<U>(&self, other: &ArcSupplier<U>) -> ArcSupplier<(T, U)>
where U: Send + 'static,

Combines this supplier with another, producing a tuple.

§Parameters
  • other - The other supplier to combine with. Note: This parameter is passed by reference, so the original supplier remains usable. Can be:
    • An ArcSupplier<U> (passed by reference)
    • Any type implementing Supplier<U> + Send
§Returns

A new ArcSupplier<(T, U)>

§Examples
use prism3_function::{ArcSupplier, Supplier};

let first = ArcSupplier::new(|| 42);
let second = ArcSupplier::new(|| "hello");

// second is passed by reference, so it remains usable
let zipped = first.zip(&second);

let mut z = zipped;
assert_eq!(z.get(), (42, "hello"));

// Both first and second still usable
let mut f = first;
let mut s = second;
assert_eq!(f.get(), 42);
assert_eq!(s.get(), "hello");
Source

pub fn memoize(&self) -> ArcSupplier<T>
where T: Clone + 'static,

Creates a memoizing supplier.

§Returns

A new memoized ArcSupplier<T>

§Examples
use prism3_function::{ArcSupplier, Supplier};
use std::sync::{Arc, Mutex};

let call_count = Arc::new(Mutex::new(0));
let call_count_clone = Arc::clone(&call_count);
let source = ArcSupplier::new(move || {
    let mut c = call_count_clone.lock().unwrap();
    *c += 1;
    42
});
let memoized = source.memoize();

let mut s = memoized;
assert_eq!(s.get(), 42); // Calls underlying function
assert_eq!(s.get(), 42); // Returns cached value
assert_eq!(*call_count.lock().unwrap(), 1);
Examples found in repository?
examples/supplier_demo.rs (line 160)
131fn demo_arc_supplier() {
132    println!("--- ArcSupplier ---");
133
134    // Basic usage
135    let supplier = ArcSupplier::new(|| 42);
136    let mut s = supplier;
137    println!("Basic: {}", s.get());
138
139    // Reusable transformations
140    let source = ArcSupplier::new(|| 10);
141    let doubled = source.map(|x| x * 2);
142    let tripled = source.map(|x| x * 3);
143
144    let mut s = source;
145    let mut d = doubled;
146    let mut t = tripled;
147    println!("Source: {}", s.get());
148    println!("Doubled: {}", d.get());
149    println!("Tripled: {}", t.get());
150
151    // Memoization
152    let call_count = Arc::new(Mutex::new(0));
153    let call_count_clone = Arc::clone(&call_count);
154    let source = ArcSupplier::new(move || {
155        let mut c = call_count_clone.lock().unwrap();
156        *c += 1;
157        println!("  Computation #{}", *c);
158        42
159    });
160    let memoized = source.memoize();
161
162    let mut m = memoized;
163    println!("First call: {}", m.get());
164    println!("Second call (cached): {}", m.get());
165    println!();
166}

Trait Implementations§

Source§

impl<T> Clone for ArcSupplier<T>

Source§

fn clone(&self) -> Self

Clones the ArcSupplier.

Creates a new instance that shares the underlying function with the original.

1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Supplier<T> for ArcSupplier<T>

Source§

fn get(&mut self) -> T

Generates and returns the next value. Read more
Source§

fn into_box(self) -> BoxSupplier<T>
where T: 'static,

Converts to BoxSupplier. Read more
Source§

fn into_rc(self) -> RcSupplier<T>
where T: 'static,

Converts to RcSupplier. Read more
Source§

fn into_arc(self) -> ArcSupplier<T>
where T: Send + 'static,

Converts to ArcSupplier. Read more
Source§

fn into_fn(self) -> impl FnMut() -> T

Converts to a closure FnMut() -> T. Read more
Source§

fn to_box(&self) -> BoxSupplier<T>
where Self: Clone + Sized + 'static, T: 'static,

Creates a BoxSupplier from a cloned supplier. Read more
Source§

fn to_rc(&self) -> RcSupplier<T>
where Self: Clone + Sized + 'static, T: 'static,

Creates an RcSupplier from a cloned supplier. Read more
Source§

fn to_arc(&self) -> ArcSupplier<T>
where Self: Clone + Sized + Send + 'static, T: Send + 'static,

Creates an ArcSupplier from a cloned supplier. Read more
Source§

fn to_fn(&self) -> impl FnMut() -> T
where Self: Clone + Sized,

Creates a closure from a cloned supplier. Read more

Auto Trait Implementations§

§

impl<T> Freeze for ArcSupplier<T>

§

impl<T> RefUnwindSafe for ArcSupplier<T>

§

impl<T> Send for ArcSupplier<T>

§

impl<T> Sync for ArcSupplier<T>

§

impl<T> Unpin for ArcSupplier<T>

§

impl<T> UnwindSafe for ArcSupplier<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.