Module supplier

Module supplier 

Source
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

  1. Returns Ownership: Supplier returns T (not &T) to avoid lifetime issues
  2. Uses &mut self: Typical scenarios (counters, generators) require state modification
  3. No ReadonlySupplier: Main use cases require state modification; value is extremely low

§Three Implementations

  • BoxSupplier<T>: Single ownership using Box<dyn FnMut() -> T>. Zero overhead, cannot be cloned. Best for one-time use and builder patterns.

  • ArcSupplier<T>: Thread-safe shared ownership using Arc<Mutex<dyn FnMut() -> T + Send>>. Can be cloned and sent across threads. Higher overhead due to locking.

  • RcSupplier<T>: Single-threaded shared ownership using Rc<RefCell<dyn FnMut() -> T>>. Can be cloned but not sent across threads. Lower overhead than ArcSupplier.

§Comparison with Other Functional Abstractions

TypeInputOutputselfModifies?Use Case
SupplierNoneT&mutYesFactory
Consumer&T()&mutYesObserver
Predicate&Tbool&selfNoFilter
Function&TR&selfNoTransform

§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.