Skip to main content

ArcSupplier

Struct ArcSupplier 

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

Thread-safe shared ownership stateless supplier.

Uses Arc<dyn Fn() -> T + Send + Sync> for thread-safe shared ownership. Lock-free - no Mutex needed! Can be cloned and sent across threads with excellent concurrent performance.

§Ownership Model

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

use qubit_function::{ArcSupplier, Supplier};

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

§Lock-Free Performance

Unlike ArcStatefulSupplier, this implementation doesn’t need Mutex. Multiple threads can call get() concurrently without lock contention, making it ideal for high-concurrency scenarios.

§Examples

§Thread-safe Factory

use qubit_function::{ArcSupplier, Supplier};
use std::thread;

let factory = ArcSupplier::new(|| {
    String::from("Hello")
});

let f1 = factory.clone();
let f2 = factory.clone();

let h1 = thread::spawn(move || f1.get());
let h2 = thread::spawn(move || f2.get());

assert_eq!(h1.join().unwrap(), "Hello");
assert_eq!(h2.join().unwrap(), "Hello");

§Reusable Transformations

use qubit_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
assert_eq!(base.get(), 10);
assert_eq!(doubled.get(), 20);
assert_eq!(tripled.get(), 30);

§Author

Haixing Hu

Implementations§

Source§

impl<T> ArcSupplier<T>

Source

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

Creates a new supplier.

Wraps the provided closure in the appropriate smart pointer type for this supplier implementation.

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

pub fn new_with_name<F>(name: &str, f: F) -> Self
where F: Fn() -> T + Send + Sync + 'static,

Creates a new named supplier.

Wraps the provided closure and assigns it a name, which is useful for debugging and logging purposes.

Source

pub fn new_with_optional_name<F>(f: F, name: Option<String>) -> Self
where F: Fn() -> T + Send + Sync + 'static,

Creates a new named supplier with an optional name.

Wraps the provided closure and assigns it an optional name.

Source

pub fn name(&self) -> Option<&str>

Gets the name of this supplier.

§Returns

Returns Some(&str) if a name was set, None otherwise.

Source

pub fn set_name(&mut self, name: &str)

Sets the name of this supplier.

§Parameters
  • name - The name to set for this supplier
Source

pub fn clear_name(&mut self)

Clears the name of this supplier.

Source

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

Maps the output using a transformation function.

§Parameters
  • mapper - The transformation function to apply
§Returns

A new $struct_name<U> with the mapped output

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

let source = ArcSupplier::new(|| 10);
let mapped = source.map(|x| x * 2);
// source is still usable
assert_eq!(mapped.get(), 20);
Examples found in repository?
examples/suppliers/stateful_supplier_demo.rs (line 163)
153fn demo_arc_supplier() {
154    println!("--- ArcSupplier ---");
155
156    // Basic usage (Fn)
157    let supplier = ArcSupplier::new(|| 42);
158    let s = supplier;
159    println!("Basic: {}", s.get());
160
161    // Reusable transformations (Fn)
162    let source = ArcSupplier::new(|| 10);
163    let doubled = source.map(|x| x * 2);
164    let tripled = source.map(|x| x * 3);
165
166    let s = source;
167    let d = doubled;
168    let t = tripled;
169    println!("Source: {}", s.get());
170    println!("Doubled: {}", d.get());
171    println!("Tripled: {}", t.get());
172
173    // Stateful with ArcStatefulSupplier (FnMut)
174    let call_count = Arc::new(Mutex::new(0));
175    let call_count_clone = Arc::clone(&call_count);
176    let source = ArcStatefulSupplier::new(move || {
177        let mut c = call_count_clone.lock().unwrap();
178        *c += 1;
179        println!("  Computation #{}", *c);
180        42
181    });
182
183    // Memoization with ArcStatefulSupplier
184    let memoized = source.memoize();
185    let mut m = memoized;
186    println!("First call: {}", m.get());
187    println!("Second call (cached): {}", m.get());
188    println!("Call count: {}", *call_count.lock().unwrap());
189    println!();
190}
Source

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

Filters output based on a predicate.

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

A new filtered $struct_name<Option<$t>>

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

let source = ArcSupplier::new(|| 42);
let filtered = source.filter(|x: &i32| x % 2 == 0);

assert_eq!(filtered.get(), Some(42));
Source

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

Combines this supplier with another, producing a tuple.

§Parameters
  • other - The other supplier to combine with
§Returns

A new $struct_name<($t, U)>

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

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

let zipped = first.zip(second);

assert_eq!(zipped.get(), (42, "hello"));
Source§

impl<T> ArcSupplier<T>

Source

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

Creates a supplier that returns a constant value.

Creates a supplier that always returns the same value. Useful for default values or placeholder implementations.

Note: This method requires T: Sync because the constant value is captured by a Fn closure which needs to be Sync for Arc.

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

Returns a new supplier instance that returns the constant value.

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

let supplier = ArcSupplier::constant(42);
assert_eq!(supplier.get(), 42);
assert_eq!(supplier.get(), 42); // Can be called multiple times

Trait Implementations§

Source§

impl<T> Clone for ArcSupplier<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for ArcSupplier<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Display for ArcSupplier<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

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

Source§

fn get(&self) -> T

Generates and returns a value. Read more
Source§

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

Converts to BoxSupplier. Read more
Source§

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

Converts to RcSupplier. Read more
Source§

fn into_arc(self) -> ArcSupplier<T>

Converts to ArcSupplier. Read more
Source§

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

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

fn into_once(self) -> BoxSupplierOnce<T>
where Self: 'static,

Converts to BoxSupplierOnce. Read more
Source§

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

Converts to BoxSupplier by cloning. Read more
Source§

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

Converts to RcSupplier by cloning. Read more
Source§

fn to_arc(&self) -> ArcSupplier<T>

Converts to ArcSupplier by cloning. Read more
Source§

fn to_fn(&self) -> impl Fn() -> T

Converts to a closure by cloning. Read more
Source§

fn to_once(&self) -> BoxSupplierOnce<T>
where Self: 'static,

Converts to BoxSupplierOnce without consuming self 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> UnsafeUnpin 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.