RcBiConsumer

Struct RcBiConsumer 

Source
pub struct RcBiConsumer<T, U> { /* private fields */ }
Expand description

RcBiConsumer struct

A bi-consumer implementation based on Rc<RefCell<dyn FnMut(&T, &U)>> for single-threaded shared ownership scenarios. This consumer provides the benefits of shared ownership without the overhead of thread safety.

§Features

  • Shared Ownership: Cloneable via Rc, multiple owners allowed
  • Single-Threaded: Not thread-safe, cannot send across threads
  • Interior Mutability: Uses RefCell for runtime borrow checking
  • No Lock Overhead: More efficient than ArcBiConsumer for single-threaded use
  • Non-Consuming API: and_then borrows &self, original remains usable

§Use Cases

Choose RcBiConsumer when:

  • Need to share bi-consumer within a single thread
  • Thread safety is not needed
  • Performance matters (avoiding lock overhead)
  • Single-threaded UI framework event handling
  • Building complex single-threaded state machines

§Performance Considerations

RcBiConsumer performs better than ArcBiConsumer in single-threaded scenarios:

  • Non-Atomic Counting: clone/drop cheaper than Arc
  • No Lock Overhead: RefCell uses runtime checking, no locks
  • Better Cache Locality: No atomic operations means better CPU cache behavior

But still has slight overhead compared to BoxBiConsumer:

  • Reference Counting: Though non-atomic, still exists
  • Runtime Borrow Checking: RefCell checks at runtime

§Safety

RcBiConsumer is not thread-safe and does not implement Send or Sync. Attempting to send it to another thread will result in a compile error. For thread-safe sharing, use ArcBiConsumer instead.

§Examples

use prism3_function::{BiConsumer, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let mut consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});
let mut clone = consumer.clone();

consumer.accept(&5, &3);
assert_eq!(*log.borrow(), vec![8]);

§Author

Haixing Hu

Implementations§

Source§

impl<T, U> RcBiConsumer<T, U>
where T: 'static, U: 'static,

Source

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

Creates a new RcBiConsumer

§Type Parameters
  • F - The closure type
§Parameters
  • f - The closure to wrap
§Returns

Returns a new RcBiConsumer<T, U> instance

§Examples
use prism3_function::{BiConsumer, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let mut consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x * 2 + *y);
});
consumer.accept(&5, &3);
assert_eq!(*log.borrow(), vec![13]);
Examples found in repository?
examples/bi_consumer_demo.rs (lines 81-83)
21fn main() {
22    println!("=== BiConsumer Demo ===\n");
23
24    // 1. BoxBiConsumer - Single ownership
25    println!("1. BoxBiConsumer - Single ownership:");
26    let log = Arc::new(Mutex::new(Vec::new()));
27    let l = log.clone();
28    let mut box_consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
29        println!("  Processing: x={}, y={}", x, y);
30        l.lock().unwrap().push(*x + *y);
31    });
32    box_consumer.accept(&10, &5);
33    println!("  Result log: {:?}\n", *log.lock().unwrap());
34
35    // 2. Method chaining with BoxBiConsumer
36    println!("2. BoxBiConsumer with method chaining:");
37    let log = Arc::new(Mutex::new(Vec::new()));
38    let l1 = log.clone();
39    let l2 = log.clone();
40    let mut chained = BoxBiConsumer::new(move |x: &i32, y: &i32| {
41        l1.lock().unwrap().push(*x + *y);
42        println!("  After first operation: sum = {}", x + y);
43    })
44    .and_then(move |x: &i32, y: &i32| {
45        l2.lock().unwrap().push(*x * *y);
46        println!("  After second operation: product = {}", x * y);
47    });
48    chained.accept(&5, &3);
49    println!("  Final log: {:?}\n", *log.lock().unwrap());
50
51    // 3. ArcBiConsumer - Thread-safe shared ownership
52    println!("3. ArcBiConsumer - Thread-safe shared ownership:");
53    let log = Arc::new(Mutex::new(Vec::new()));
54    let l = log.clone();
55    let arc_consumer = ArcBiConsumer::new(move |x: &i32, y: &i32| {
56        l.lock().unwrap().push(*x + *y);
57        println!("  Thread {:?}: sum = {}", thread::current().id(), x + y);
58    });
59
60    let consumer1 = arc_consumer.clone();
61    let consumer2 = arc_consumer.clone();
62
63    let handle1 = thread::spawn(move || {
64        let mut c = consumer1;
65        c.accept(&10, &5);
66    });
67
68    let handle2 = thread::spawn(move || {
69        let mut c = consumer2;
70        c.accept(&20, &8);
71    });
72
73    handle1.join().unwrap();
74    handle2.join().unwrap();
75    println!("  Final log: {:?}\n", *log.lock().unwrap());
76
77    // 4. RcBiConsumer - Single-threaded shared ownership
78    println!("4. RcBiConsumer - Single-threaded shared ownership:");
79    let log = Rc::new(RefCell::new(Vec::new()));
80    let l = log.clone();
81    let rc_consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
82        l.borrow_mut().push(*x + *y);
83    });
84
85    let mut clone1 = rc_consumer.clone();
86    let mut clone2 = rc_consumer.clone();
87
88    clone1.accept(&5, &3);
89    println!("  After first use: {:?}", *log.borrow());
90
91    clone2.accept(&7, &2);
92    println!("  After second use: {:?}\n", *log.borrow());
93
94    // 5. Working with closures directly
95    println!("5. Working with closures directly:");
96    let log = Arc::new(Mutex::new(Vec::new()));
97    let l = log.clone();
98    let mut closure = move |x: &i32, y: &i32| {
99        let sum = *x + *y;
100        l.lock().unwrap().push(sum);
101    };
102    closure.accept(&10, &20);
103    println!("  After closure: {:?}\n", *log.lock().unwrap());
104
105    // 6. Conditional BiConsumer
106    println!("6. Conditional BiConsumer:");
107    let log = Arc::new(Mutex::new(Vec::new()));
108    let l = log.clone();
109    let mut conditional = BoxBiConsumer::new(move |x: &i32, y: &i32| {
110        l.lock().unwrap().push(*x + *y);
111    })
112    .when(|x: &i32, y: &i32| *x > 0 && *y > 0);
113
114    conditional.accept(&5, &3);
115    println!("  Positive values: {:?}", *log.lock().unwrap());
116
117    conditional.accept(&-5, &3);
118    println!("  Negative value (unchanged): {:?}\n", *log.lock().unwrap());
119
120    // 7. Conditional branch BiConsumer
121    println!("7. Conditional branch BiConsumer:");
122    let log = Arc::new(Mutex::new(Vec::new()));
123    let l1 = log.clone();
124    let l2 = log.clone();
125    let mut branch = BoxBiConsumer::new(move |x: &i32, _y: &i32| {
126        l1.lock().unwrap().push(*x);
127    })
128    .when(|x: &i32, y: &i32| *x > *y)
129    .or_else(move |_x: &i32, y: &i32| {
130        l2.lock().unwrap().push(*y);
131    });
132
133    branch.accept(&15, &10);
134    println!("  When x > y: {:?}", *log.lock().unwrap());
135
136    branch.accept(&5, &10);
137    println!("  When x <= y: {:?}\n", *log.lock().unwrap());
138
139    // 8. Accumulating statistics
140    println!("8. Accumulating statistics:");
141    let count = Arc::new(Mutex::new(0));
142    let sum = Arc::new(Mutex::new(0));
143    let c = count.clone();
144    let s = sum.clone();
145    let mut stats_consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
146        *c.lock().unwrap() += 1;
147        *s.lock().unwrap() += x + y;
148    });
149
150    stats_consumer.accept(&5, &3);
151    stats_consumer.accept(&10, &2);
152    stats_consumer.accept(&7, &8);
153
154    println!("  Count: {}", *count.lock().unwrap());
155    println!("  Sum: {}\n", *sum.lock().unwrap());
156
157    // 9. Name support
158    println!("9. Name support:");
159    let mut named_consumer = BoxBiConsumer::<i32, i32>::noop();
160    println!("  Initial name: {:?}", named_consumer.name());
161
162    named_consumer.set_name("sum_calculator");
163    println!("  After setting name: {:?}", named_consumer.name());
164    println!("  Display: {}\n", named_consumer);
165
166    println!("=== Demo Complete ===");
167}
Source

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

Creates a new RcBiConsumer with a name

§Type Parameters
  • F - The closure type
§Parameters
  • name - The name of the consumer
  • f - The closure to wrap
§Returns

Returns a new RcBiConsumer<T, U> instance with the specified name

§Examples
use prism3_function::{BiConsumer, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let mut consumer = RcBiConsumer::new_with_name("sum_logger", move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});
assert_eq!(consumer.name(), Some("sum_logger"));
consumer.accept(&5, &3);
assert_eq!(*log.borrow(), vec![8]);
Source

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

Gets the name of the consumer

§Returns

Returns the consumer’s name, or None if not set

Source

pub fn set_name(&mut self, name: impl Into<String>)

Sets the name of the consumer

§Parameters
  • name - The name to set
Source

pub fn to_fn(&self) -> impl FnMut(&T, &U)
where T: 'static, U: 'static,

Converts to a closure (without consuming self)

Creates a new closure that calls the underlying function via Rc.

§Returns

Returns a closure implementing FnMut(&T, &U)

§Examples
use prism3_function::{BiConsumer, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});

let mut func = consumer.to_fn();
func(&5, &3);
assert_eq!(*log.borrow(), vec![8]);
Source

pub fn and_then(&self, next: &RcBiConsumer<T, U>) -> RcBiConsumer<T, U>

Chains another RcBiConsumer in sequence

Returns a new consumer executing the current operation first, then the next operation. Borrows &self, does not consume the original consumer.

§Parameters
  • next - The consumer to execute after the current operation
§Returns

Returns a new composed RcBiConsumer<T, U>

§Examples
use prism3_function::{BiConsumer, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l1 = log.clone();
let l2 = log.clone();
let first = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l1.borrow_mut().push(*x + *y);
});
let second = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l2.borrow_mut().push(*x * *y);
});

let mut chained = first.and_then(&second);

// first and second still usable after chaining
chained.accept(&5, &3);
assert_eq!(*log.borrow(), vec![8, 15]);
Source

pub fn when<P>(&self, predicate: P) -> RcConditionalBiConsumer<T, U>
where P: BiPredicate<T, U> + 'static,

Creates a conditional bi-consumer (single-threaded shared version)

Returns a bi-consumer that only executes when a predicate is satisfied.

§Type Parameters
  • P - The predicate type
§Parameters
  • predicate - The condition to check. Note: This parameter is passed by value and will transfer ownership. If you need to preserve the original bi-predicate, clone it first (if it implements Clone). Can be:
    • A closure: |x: &T, y: &U| -> bool
    • A function pointer: fn(&T, &U) -> bool
    • An RcBiPredicate<T, U>
    • A BoxBiPredicate<T, U>
    • Any type implementing BiPredicate<T, U>
§Returns

Returns RcConditionalBiConsumer<T, U>

§Examples
use prism3_function::{BiConsumer, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});
let conditional = consumer.when(|x: &i32, y: &i32| *x > 0 && *y > 0);

let conditional_clone = conditional.clone();

let mut positive = 5;
let mut m = conditional;
m.accept(&positive, &3);
assert_eq!(*log.borrow(), vec![8]);

Trait Implementations§

Source§

impl<T, U> BiConsumer<T, U> for RcBiConsumer<T, U>

Source§

fn accept(&mut self, first: &T, second: &U)

Performs the consumption operation Read more
Source§

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

Converts to BoxBiConsumer Read more
Source§

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

Converts to RcBiConsumer Read more
Source§

fn into_fn(self) -> impl FnMut(&T, &U)
where T: 'static, U: 'static,

Converts bi-consumer to a closure Read more
Source§

fn to_box(&self) -> BoxBiConsumer<T, U>
where T: 'static, U: 'static,

Converts to BoxBiConsumer (non-consuming) Read more
Source§

fn to_rc(&self) -> RcBiConsumer<T, U>
where T: 'static, U: 'static,

Converts to RcBiConsumer (non-consuming) Read more
Source§

fn to_fn(&self) -> impl FnMut(&T, &U)
where T: 'static, U: 'static,

Converts to closure (non-consuming) Read more
Source§

fn into_arc(self) -> ArcBiConsumer<T, U>
where Self: Sized + Send + 'static, T: Send + 'static, U: Send + 'static,

Converts to ArcBiConsumer Read more
Source§

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

Converts to ArcBiConsumer (non-consuming) Read more
Source§

impl<T, U> BiConsumerOnce<T, U> for RcBiConsumer<T, U>
where T: 'static, U: 'static,

Source§

fn accept_once(self, first: &T, second: &U)

Performs the one-time consumption operation

Executes the underlying function once and consumes the consumer. After calling this method, the consumer is no longer available.

§Parameters
  • first - Reference to the first value to consume
  • second - Reference to the second value to consume
§Examples
use prism3_function::{BiConsumerOnce, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});
consumer.accept_once(&5, &3);
assert_eq!(*log.borrow(), vec![8]);
Source§

fn into_box_once(self) -> BoxBiConsumerOnce<T, U>
where Self: Sized + 'static, T: 'static, U: 'static,

Converts to BoxBiConsumerOnce

⚠️ Consumes self: Original consumer becomes unavailable after calling this method.

§Returns

Returns the wrapped BoxBiConsumerOnce<T, U>

§Examples
use prism3_function::{BiConsumerOnce, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});
let box_once = consumer.into_box_once();
box_once.accept_once(&5, &3);
assert_eq!(*log.borrow(), vec![8]);
Source§

fn into_fn_once(self) -> impl FnOnce(&T, &U)
where Self: Sized + 'static, T: 'static, U: 'static,

Converts to a closure

⚠️ Consumes self: Original consumer becomes unavailable after calling this method.

Converts the bi-consumer to a closure usable with standard library methods requiring FnOnce.

§Returns

Returns a closure implementing FnOnce(&T, &U)

§Examples
use prism3_function::{BiConsumerOnce, RcBiConsumer};
use std::rc::Rc;
use std::cell::RefCell;

let log = Rc::new(RefCell::new(Vec::new()));
let l = log.clone();
let consumer = RcBiConsumer::new(move |x: &i32, y: &i32| {
    l.borrow_mut().push(*x + *y);
});
let func = consumer.into_fn_once();
func(&5, &3);
assert_eq!(*log.borrow(), vec![8]);
Source§

fn to_box_once(&self) -> BoxBiConsumerOnce<T, U>
where Self: Sized + Clone + 'static, T: 'static, U: 'static,

Convert to BoxBiConsumerOnce without consuming self Read more
Source§

fn to_fn_once(&self) -> impl FnOnce(&T, &U)
where Self: Sized + Clone + 'static, T: 'static, U: 'static,

Convert to closure without consuming self Read more
Source§

impl<T, U> Clone for RcBiConsumer<T, U>

Source§

fn clone(&self) -> Self

Clones the RcBiConsumer

Creates a new RcBiConsumer sharing the underlying function with the original instance.

1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<T, U> Debug for RcBiConsumer<T, U>

Source§

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

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

impl<T, U> Display for RcBiConsumer<T, U>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T, U> Freeze for RcBiConsumer<T, U>

§

impl<T, U> !RefUnwindSafe for RcBiConsumer<T, U>

§

impl<T, U> !Send for RcBiConsumer<T, U>

§

impl<T, U> !Sync for RcBiConsumer<T, U>

§

impl<T, U> Unpin for RcBiConsumer<T, U>

§

impl<T, U> !UnwindSafe for RcBiConsumer<T, U>

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.