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
RefCellfor runtime borrow checking - No Lock Overhead: More efficient than
ArcBiConsumerfor single-threaded use - Non-Consuming API:
and_thenborrows&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:
RefCelluses 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:
RefCellchecks 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,
impl<T, U> RcBiConsumer<T, U>where
T: 'static,
U: 'static,
Sourcepub fn new<F>(f: F) -> Self
pub fn new<F>(f: F) -> Self
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?
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}Sourcepub fn new_with_name<F>(name: &str, f: F) -> Self
pub fn new_with_name<F>(name: &str, f: F) -> Self
Creates a new RcBiConsumer with a name
§Type Parameters
F- The closure type
§Parameters
name- The name of the consumerf- 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]);Sourcepub fn to_fn(&self) -> impl FnMut(&T, &U)where
T: 'static,
U: 'static,
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]);Sourcepub fn and_then(&self, next: &RcBiConsumer<T, U>) -> RcBiConsumer<T, U>
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]);Sourcepub fn when<P>(&self, predicate: P) -> RcConditionalBiConsumer<T, U>where
P: BiPredicate<T, U> + 'static,
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 implementsClone). 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>
- A closure:
§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>
impl<T, U> BiConsumer<T, U> for RcBiConsumer<T, U>
Source§fn into_box(self) -> BoxBiConsumer<T, U>where
T: 'static,
U: 'static,
fn into_box(self) -> BoxBiConsumer<T, U>where
T: 'static,
U: 'static,
Source§fn into_rc(self) -> RcBiConsumer<T, U>where
T: 'static,
U: 'static,
fn into_rc(self) -> RcBiConsumer<T, U>where
T: 'static,
U: 'static,
Source§fn into_fn(self) -> impl FnMut(&T, &U)where
T: 'static,
U: 'static,
fn into_fn(self) -> impl FnMut(&T, &U)where
T: 'static,
U: 'static,
Source§fn to_box(&self) -> BoxBiConsumer<T, U>where
T: 'static,
U: 'static,
fn to_box(&self) -> BoxBiConsumer<T, U>where
T: 'static,
U: 'static,
Source§fn to_rc(&self) -> RcBiConsumer<T, U>where
T: 'static,
U: 'static,
fn to_rc(&self) -> RcBiConsumer<T, U>where
T: 'static,
U: 'static,
Source§fn to_fn(&self) -> impl FnMut(&T, &U)where
T: 'static,
U: 'static,
fn to_fn(&self) -> impl FnMut(&T, &U)where
T: 'static,
U: 'static,
Source§fn into_arc(self) -> ArcBiConsumer<T, U>
fn into_arc(self) -> ArcBiConsumer<T, U>
Source§impl<T, U> BiConsumerOnce<T, U> for RcBiConsumer<T, U>where
T: 'static,
U: 'static,
impl<T, U> BiConsumerOnce<T, U> for RcBiConsumer<T, U>where
T: 'static,
U: 'static,
Source§fn accept_once(self, first: &T, second: &U)
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 consumesecond- 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,
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,
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]);