BoxConditionalBiConsumer

Struct BoxConditionalBiConsumer 

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

BoxConditionalBiConsumer struct

A conditional bi-consumer that only executes when a predicate is satisfied. Uses BoxBiConsumer and BoxBiPredicate for single ownership semantics.

This type is typically created by calling BoxBiConsumer::when() and is designed to work with the or_else() method to create if-then-else logic.

§Features

  • Single Ownership: Not cloneable, consumes self on use
  • Conditional Execution: Only consumes when predicate returns true
  • Chainable: Can add or_else branch to create if-then-else logic
  • Implements BiConsumer: Can be used anywhere a BiConsumer is expected

§Examples

§Basic Conditional Execution

use prism3_function::{BiConsumer, BoxBiConsumer};
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l.lock().unwrap().push(*x + *y);
});
let mut conditional = consumer.when(|x: &i32, y: &i32| *x > 0 && *y > 0);

conditional.accept(&5, &3);
assert_eq!(*log.lock().unwrap(), vec![8]); // Executed

conditional.accept(&-5, &3);
assert_eq!(*log.lock().unwrap(), vec![8]); // Not executed

§With or_else Branch

use prism3_function::{BiConsumer, BoxBiConsumer};
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l1 = log.clone();
let l2 = log.clone();
let mut consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l1.lock().unwrap().push(*x + *y);
}).when(|x: &i32, y: &i32| *x > 0 && *y > 0)
  .or_else(move |x: &i32, y: &i32| {
    l2.lock().unwrap().push(*x * *y);
});

consumer.accept(&5, &3);
assert_eq!(*log.lock().unwrap(), vec![8]); // when branch executed

consumer.accept(&-5, &3);
assert_eq!(*log.lock().unwrap(), vec![8, -15]); // or_else branch executed

§Author

Haixing Hu

Implementations§

Source§

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

Source

pub fn and_then<C>(self, next: C) -> BoxBiConsumer<T, U>
where C: BiConsumer<T, U> + 'static,

Chains another consumer in sequence

Combines the current conditional consumer with another consumer into a new consumer. The current conditional consumer executes first, followed by the next consumer.

§Parameters
  • next - The next consumer to execute. Note: This parameter is passed by value and will transfer ownership. If you need to preserve the original consumer, clone it first (if it implements Clone). Can be:
    • A closure: |x: &T, y: &U|
    • A BoxBiConsumer<T, U>
    • An ArcBiConsumer<T, U>
    • An RcBiConsumer<T, U>
    • Any type implementing BiConsumer<T, U>
§Returns

Returns a new BoxBiConsumer<T, U>

§Examples
§Direct value passing (ownership transfer)
use prism3_function::{BiConsumer, BoxBiConsumer};
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l1 = log.clone();
let l2 = log.clone();
let cond = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l1.lock().unwrap().push(*x + *y);
}).when(|x: &i32, y: &i32| *x > 0 && *y > 0);
let second = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l2.lock().unwrap().push(*x * *y);
});

// second is moved here
let mut chained = cond.and_then(second);
chained.accept(&5, &3);
assert_eq!(*log.lock().unwrap(), vec![8, 15]);
// second.accept(&2, &3); // Would not compile - moved
§Preserving original with clone
use prism3_function::{BiConsumer, BoxBiConsumer};
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l1 = log.clone();
let l2 = log.clone();
let cond = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l1.lock().unwrap().push(*x + *y);
}).when(|x: &i32, y: &i32| *x > 0 && *y > 0);
let second = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l2.lock().unwrap().push(*x * *y);
});

// Clone to preserve original
let mut chained = cond.and_then(second.clone());
chained.accept(&5, &3);
assert_eq!(*log.lock().unwrap(), vec![8, 15]);

// Original still usable
second.accept(&2, &3);
assert_eq!(*log.lock().unwrap(), vec![8, 15, 6]);
Source

pub fn or_else<C>(self, else_consumer: C) -> BoxBiConsumer<T, U>
where C: BiConsumer<T, U> + 'static,

Adds an else branch

Executes the original consumer when the condition is satisfied, otherwise executes else_consumer.

§Parameters
  • else_consumer - The consumer for the else branch. Note: This parameter is passed by value and will transfer ownership. If you need to preserve the original consumer, clone it first (if it implements Clone). Can be:
    • A closure: |x: &T, y: &U|
    • A BoxBiConsumer<T, U>
    • An RcBiConsumer<T, U>
    • An ArcBiConsumer<T, U>
    • Any type implementing BiConsumer<T, U>
§Returns

Returns the composed BoxBiConsumer<T, U>

§Examples
use prism3_function::{BiConsumer, BoxBiConsumer};
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l1 = log.clone();
let l2 = log.clone();
let mut consumer = BoxBiConsumer::new(move |x: &i32, y: &i32| {
    l1.lock().unwrap().push(*x + *y);
}).when(|x: &i32, y: &i32| *x > 0 && *y > 0)
  .or_else(move |x: &i32, y: &i32| {
    l2.lock().unwrap().push(*x * *y);
});

consumer.accept(&5, &3);
assert_eq!(*log.lock().unwrap(), vec![8]); // Condition satisfied

consumer.accept(&-5, &3);
assert_eq!(*log.lock().unwrap(), vec![8, -15]); // Condition not satisfied
Examples found in repository?
examples/bi_consumer_demo.rs (lines 129-131)
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}

Trait Implementations§

Source§

impl<T, U> BiConsumer<T, U> for BoxConditionalBiConsumer<T, U>
where T: 'static, U: 'static,

Source§

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

Performs the consumption operation Read more
Source§

fn into_box(self) -> BoxBiConsumer<T, U>

Converts to BoxBiConsumer Read more
Source§

fn into_rc(self) -> RcBiConsumer<T, U>

Converts to RcBiConsumer Read more
Source§

fn into_fn(self) -> impl FnMut(&T, &U)

Converts bi-consumer to a closure 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

Auto Trait Implementations§

§

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

§

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

§

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

§

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

§

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

§

impl<T, U> !UnwindSafe for BoxConditionalBiConsumer<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> 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, 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.