Skip to main content

ConsumerOnce

Trait ConsumerOnce 

Source
pub trait ConsumerOnce<T> {
    // Required method
    fn accept(self, value: &T);

    // Provided methods
    fn into_box(self) -> BoxConsumerOnce<T>
       where Self: Sized + 'static { ... }
    fn into_fn(self) -> impl FnOnce(&T)
       where Self: Sized + 'static { ... }
    fn to_box(&self) -> BoxConsumerOnce<T>
       where Self: Sized + Clone + 'static { ... }
    fn to_fn(&self) -> impl FnOnce(&T)
       where Self: Sized + Clone + 'static { ... }
}
Expand description

ConsumerOnce trait - Unified one-time consumer interface

It is similar to the FnOnce(&T) trait in the standard library.

Defines the core behavior of all one-time consumer types. Similar to consumers implementing FnOnce(&T), executes operations that accept a value reference but return no result (only side effects), consuming itself in the process.

§Automatic Implementation

  • All closures implementing FnOnce(&T)
  • BoxConsumerOnce<T>

§Features

  • Unified Interface: All consumer types share the same accept method signature
  • Automatic Implementation: Closures automatically implement this trait with zero overhead
  • Type Conversion: Can be converted to BoxConsumerOnce
  • Generic Programming: Write functions that work with any one-time consumer type

§Examples

use qubit_function::{ConsumerOnce, BoxConsumerOnce};
use std::sync::{Arc, Mutex};

fn apply_consumer<C: ConsumerOnce<i32>>(consumer: C, value: &i32) {
    consumer.accept(value);
}

let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let box_con = BoxConsumerOnce::new(move |x: &i32| {
    l.lock().unwrap().push(*x);
});
apply_consumer(box_con, &5);
assert_eq!(*log.lock().unwrap(), vec![5]);

§Author

Haixing Hu

Required Methods§

Source

fn accept(self, value: &T)

Execute one-time consumption operation

Executes an operation on the given reference. The operation typically reads the input value or produces side effects, but does not modify the input value itself. Consumes self.

§Parameters
  • value - Reference to the value to be consumed
§Examples
use qubit_function::{ConsumerOnce, BoxConsumerOnce};

let consumer = BoxConsumerOnce::new(|x: &i32| println!("{}", x));
consumer.accept(&5);

Provided Methods§

Source

fn into_box(self) -> BoxConsumerOnce<T>
where Self: Sized + 'static,

Convert to BoxConsumerOnce

⚠️ Consumes self: The original consumer will be unavailable after calling this method.

§Default Implementation

The default implementation wraps self in a BoxConsumerOnce by calling accept on the consumer. Types can override this method to provide more efficient conversions.

§Returns

Returns the wrapped BoxConsumerOnce<T>

§Examples
use qubit_function::ConsumerOnce;
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let closure = move |x: &i32| {
    l.lock().unwrap().push(*x);
};
let box_consumer = closure.into_box();
box_consumer.accept(&5);
assert_eq!(*log.lock().unwrap(), vec![5]);
Examples found in repository?
examples/consumers/consumer_once_demo.rs (line 141)
23fn main() {
24    println!("=== ConsumerOnce Demo ===\n");
25
26    // 1. BoxConsumerOnce - Single ownership, one-time use
27    println!("1. BoxConsumerOnce - Single ownership");
28    {
29        let log = Arc::new(Mutex::new(Vec::new()));
30        let l = log.clone();
31        let consumer = BoxConsumerOnce::new(move |x: &i32| {
32            l.lock().unwrap().push(*x);
33            println!("  BoxConsumerOnce consumed: {}", x);
34        });
35        consumer.accept(&42);
36        println!("  Log: {:?}\n", *log.lock().unwrap());
37    }
38
39    // 2. BoxConsumerOnce - Method chaining
40    println!("2. BoxConsumerOnce - Method chaining");
41    {
42        let log = Arc::new(Mutex::new(Vec::new()));
43        let l1 = log.clone();
44        let l2 = log.clone();
45        let l3 = log.clone();
46        let chained = BoxConsumerOnce::new(move |x: &i32| {
47            l1.lock().unwrap().push(*x * 2);
48            println!("  Step 1: {} * 2 = {}", x, x * 2);
49        })
50        .and_then(move |x: &i32| {
51            l2.lock().unwrap().push(*x + 10);
52            println!("  Step 2: {} + 10 = {}", x, x + 10);
53        })
54        .and_then(move |x: &i32| {
55            l3.lock().unwrap().push(*x - 1);
56            println!("  Step 3: {} - 1 = {}", x, x - 1);
57        });
58        chained.accept(&5);
59        println!("  Log: {:?}\n", *log.lock().unwrap());
60    }
61
62    // 3. BoxConsumerOnce - Factory methods
63    println!("3. BoxConsumerOnce - Factory methods");
64    {
65        // No-op consumer
66        let noop = BoxConsumerOnce::<i32>::noop();
67        noop.accept(&42);
68        println!("  No-op consumer executed (no output)");
69
70        // Print consumer
71        print!("  Print consumer: ");
72        let print = BoxConsumerOnce::new(|x: &i32| println!("{}", x));
73        print.accept(&42);
74
75        // Print with prefix
76        print!("  Print with prefix: ");
77        let print_with = BoxConsumerOnce::new(|x: &i32| println!("Value: {}", x));
78        print_with.accept(&42);
79
80        // Conditional consumer
81        let log = Arc::new(Mutex::new(Vec::new()));
82        let l = log.clone();
83        let conditional = BoxConsumerOnce::new(move |x: &i32| {
84            l.lock().unwrap().push(*x * 2);
85        })
86        .when(|x: &i32| *x > 0);
87        conditional.accept(&5);
88        println!("  Conditional (positive): {:?}", *log.lock().unwrap());
89
90        let log = Arc::new(Mutex::new(Vec::new()));
91        let l = log.clone();
92        let conditional = BoxConsumerOnce::new(move |x: &i32| {
93            l.lock().unwrap().push(*x * 2);
94        })
95        .when(|x: &i32| *x > 0);
96        conditional.accept(&-5);
97        println!("  Conditional (negative): {:?}\n", *log.lock().unwrap());
98    }
99
100    // 4. Closure usage
101    println!("4. Closure usage");
102    {
103        let log = Arc::new(Mutex::new(Vec::new()));
104        let l = log.clone();
105        let closure = move |x: &i32| {
106            l.lock().unwrap().push(*x * 2);
107            println!("  Closure consumed: {}", x);
108        };
109        closure.accept(&42);
110        println!("  Log: {:?}\n", *log.lock().unwrap());
111    }
112
113    // 5. Closure chaining
114    println!("5. Closure chaining");
115    {
116        let log = Arc::new(Mutex::new(Vec::new()));
117        let l1 = log.clone();
118        let l2 = log.clone();
119        let chained = (move |x: &i32| {
120            l1.lock().unwrap().push(*x * 2);
121            println!("  Closure 1: {} * 2 = {}", x, x * 2);
122        })
123        .and_then(move |x: &i32| {
124            l2.lock().unwrap().push(*x + 10);
125            println!("  Closure 2: {} + 10 = {}", x, x + 10);
126        });
127        chained.accept(&5);
128        println!("  Log: {:?}\n", *log.lock().unwrap());
129    }
130
131    // 6. Type conversions
132    println!("6. Type conversions");
133    {
134        let log = Arc::new(Mutex::new(Vec::new()));
135
136        // Closure to BoxConsumerOnce
137        let l = log.clone();
138        let closure = move |x: &i32| {
139            l.lock().unwrap().push(*x);
140        };
141        let box_consumer = closure.into_box();
142        box_consumer.accept(&1);
143        println!("  BoxConsumerOnce: {:?}", *log.lock().unwrap());
144    }
145
146    // 7. Using with iterators (BoxConsumerOnce)
147    println!("7. Using with iterators");
148    {
149        let log = Arc::new(Mutex::new(Vec::new()));
150        let l = log.clone();
151        let consumer = BoxConsumerOnce::new(move |x: &i32| {
152            l.lock().unwrap().push(*x * 2);
153        });
154        // Note: This will panic because BoxConsumerOnce can only be called once
155        // vec![1, 2, 3, 4, 5].iter().for_each(consumer.into_fn());
156        consumer.accept(&1);
157        println!(
158            "  BoxConsumerOnce with single value: {:?}\n",
159            *log.lock().unwrap()
160        );
161    }
162
163    println!("=== Demo Complete ===");
164}
Source

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

Convert to closure

⚠️ Consumes self: The original consumer will be unavailable after calling this method.

Converts a one-time consumer to a closure that can be used directly in places where the standard library requires FnOnce.

§Default Implementation

The default implementation creates a closure that captures self and calls its accept method. Types can override this method to provide more efficient conversions.

§Returns

Returns a closure implementing FnOnce(&T)

§Examples
use qubit_function::ConsumerOnce;
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let closure = move |x: &i32| {
    l.lock().unwrap().push(*x * 2);
};
let func = closure.into_fn();
func(&5);
assert_eq!(*log.lock().unwrap(), vec![10]);
Source

fn to_box(&self) -> BoxConsumerOnce<T>
where Self: Sized + Clone + 'static,

Convert to BoxConsumerOnce without consuming self

⚠️ Requires Clone: This method requires Self to implement Clone. Clones the current consumer and wraps it in a BoxConsumerOnce.

§Default Implementation

The default implementation clones self and then calls into_box() on the clone. Types can override this method to provide more efficient conversions.

§Returns

Returns the wrapped BoxConsumerOnce<T>

§Examples
use qubit_function::ConsumerOnce;
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let closure = move |x: &i32| {
    l.lock().unwrap().push(*x);
};
let box_consumer = closure.to_box();
box_consumer.accept(&5);
assert_eq!(*log.lock().unwrap(), vec![5]);
Source

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

Convert to closure without consuming self

⚠️ Requires Clone: This method requires Self to implement Clone. Clones the current consumer and then converts the clone to a closure.

§Default Implementation

The default implementation clones self and then calls into_fn() on the clone. Types can override this method to provide more efficient conversions.

§Returns

Returns a closure implementing FnOnce(&T)

§Examples
use qubit_function::ConsumerOnce;
use std::sync::{Arc, Mutex};

let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
let closure = move |x: &i32| {
    l.lock().unwrap().push(*x * 2);
};
let func = closure.to_fn();
func(&5);
assert_eq!(*log.lock().unwrap(), vec![10]);

Implementors§