qubit-function 0.11.0

Functional programming traits and Box/Rc/Arc adapters for Rust, inspired by Java functional interfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/
//! # StatefulSupplier Types
//!
//! Provides stateful supplier implementations that generate and return values
//! without taking input while allowing mutable internal state.
//!
//! # Overview
//!
//! A **StatefulSupplier** is a functional abstraction equivalent to
//! `FnMut() -> T`: it generates values without accepting input and may update
//! its own internal state between calls. It is useful for counters,
//! sequences, generators, and memoized computations.
//!
//! For stateless factories and constants that only need `Fn() -> T`, use
//! [`Supplier`](crate::Supplier).
//!
//! # Core Design Principles
//!
//! 1. **Returns Ownership**: `StatefulSupplier` returns `T` (not `&T`) to
//!    avoid lifetime issues
//! 2. **Uses `&mut self`**: Typical scenarios (counters, generators)
//!    require state modification
//! 3. **Separate stateless API**: `Supplier` covers lock-free stateless
//!    factories, while `StatefulSupplier` covers stateful generation
//!
//! # Three Implementations
//!
//! - **`BoxStatefulSupplier<T>`**: Single ownership using `Box<dyn FnMut()
//!   -> T>`. Zero overhead, cannot be cloned. Best for one-time use
//!   and builder patterns.
//!
//! - **`ArcStatefulSupplier<T>`**: Thread-safe shared ownership using
//!   `Arc<Mutex<dyn FnMut() -> T + Send>>`. Can be cloned and sent
//!   across threads. Higher overhead due to locking.
//!
//! - **`RcStatefulSupplier<T>`**: Single-threaded shared ownership using
//!   `Rc<RefCell<dyn FnMut() -> T>>`. Can be cloned but not sent
//!   across threads. Lower overhead than `ArcStatefulSupplier`.
//!
//! # Comparison with Other Functional Abstractions
//!
//! | Type      | Input | Output | self      | Modifies? | Use Case      |
//! |-----------|-------|--------|-----------|-----------|---------------|
//! | Supplier  | None  | `T`    | `&mut`    | Yes       | Factory       |
//! | Consumer  | `&T`  | `()`   | `&mut`    | Yes       | Observer      |
//! | Predicate | `&T`  | `bool` | `&self`   | No        | Filter        |
//! | Function  | `&T`  | `R`    | `&self`   | No        | Transform     |
//!
//! # Examples
//!
//! ## Basic Counter
//!
//! ```rust
//! use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
//!
//! let mut counter = 0;
//! let mut supplier = BoxStatefulSupplier::new(move || {
//!     counter += 1;
//!     counter
//! });
//!
//! assert_eq!(supplier.get(), 1);
//! assert_eq!(supplier.get(), 2);
//! assert_eq!(supplier.get(), 3);
//! ```
//!
//! ## Method Chaining
//!
//! ```rust
//! use qubit_function::{BoxStatefulSupplier, StatefulSupplier};
//!
//! let mut pipeline = BoxStatefulSupplier::new(|| 10)
//!     .map(|x| x * 2)
//!     .map(|x| x + 5);
//!
//! assert_eq!(pipeline.get(), 25);
//! ```
//!
//! ## Thread-safe Sharing
//!
//! ```rust
//! use qubit_function::{ArcStatefulSupplier, StatefulSupplier};
//! use std::sync::{Arc, Mutex};
//! use std::thread;
//!
//! let counter = Arc::new(Mutex::new(0));
//! let counter_clone = Arc::clone(&counter);
//!
//! let supplier = ArcStatefulSupplier::new(move || {
//!     let mut c = counter_clone.lock().unwrap();
//!     *c += 1;
//!     *c
//! });
//!
//! let mut s1 = supplier.clone();
//! let mut s2 = supplier.clone();
//!
//! let h1 = thread::spawn(move || s1.get());
//! let h2 = thread::spawn(move || s2.get());
//!
//! let v1 = h1.join().unwrap();
//! let v2 = h2.join().unwrap();
//!
//! assert!(v1 != v2);
//! assert_eq!(*counter.lock().unwrap(), 2);
//! ```
//!
//! # Author
//!
//! Haixing Hu
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use parking_lot::Mutex;

use crate::macros::{
    impl_arc_conversions,
    impl_box_conversions,
    impl_closure_trait,
    impl_rc_conversions,
};
use crate::predicates::predicate::Predicate;
use crate::suppliers::{
    macros::{
        impl_box_supplier_methods,
        impl_shared_supplier_methods,
        impl_supplier_clone,
        impl_supplier_common_methods,
        impl_supplier_debug_display,
    },
    supplier_once::BoxSupplierOnce,
};
use crate::transformers::transformer::Transformer;

mod box_stateful_supplier;
pub use box_stateful_supplier::BoxStatefulSupplier;
mod rc_stateful_supplier;
pub use rc_stateful_supplier::RcStatefulSupplier;
mod arc_stateful_supplier;
pub use arc_stateful_supplier::ArcStatefulSupplier;
mod fn_stateful_supplier_ops;
pub use fn_stateful_supplier_ops::FnStatefulSupplierOps;

// ==========================================================================
// Supplier Trait
// ==========================================================================

/// Supplier trait: generates and returns values without input.
///
/// The core abstraction for value generation. Similar to Java's
/// `Supplier<T>` interface, it produces values without taking any
/// input parameters.
///
/// # Key Characteristics
///
/// - **No input parameters**: Pure value generation
/// - **Mutable access**: Uses `&mut self` to allow state changes
/// - **Returns ownership**: Returns `T` (not `&T`) to avoid lifetime
///   issues
/// - **Can modify state**: Commonly used for counters, sequences,
///   and generators
///
/// # Automatically Implemented for Closures
///
/// All `FnMut() -> T` closures automatically implement this trait,
/// enabling seamless integration with both raw closures and wrapped
/// supplier types.
///
/// # Examples
///
/// ## Using with Generic Functions
///
/// ```rust
/// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
///
/// fn call_twice<S: StatefulSupplier<i32>>(supplier: &mut S) -> (i32, i32) {
///     (supplier.get(), supplier.get())
/// }
///
/// let mut s = BoxStatefulSupplier::new(|| 42);
/// assert_eq!(call_twice(&mut s), (42, 42));
///
/// let mut closure = || 100;
/// assert_eq!(call_twice(&mut closure), (100, 100));
/// ```
///
/// ## Stateful Supplier
///
/// ```rust
/// use qubit_function::StatefulSupplier;
///
/// let mut counter = 0;
/// let mut stateful = || {
///     counter += 1;
///     counter
/// };
///
/// assert_eq!(stateful.get(), 1);
/// assert_eq!(stateful.get(), 2);
/// ```
///
/// # Author
///
/// Haixing Hu
pub trait StatefulSupplier<T> {
    /// Generates and returns the next value.
    ///
    /// Executes the underlying function and returns the generated
    /// value. Uses `&mut self` because suppliers typically involve
    /// state changes (counters, sequences, etc.).
    ///
    /// # Returns
    ///
    /// The generated value of type `T`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
    ///
    /// let mut supplier = BoxStatefulSupplier::new(|| 42);
    /// assert_eq!(supplier.get(), 42);
    /// ```
    fn get(&mut self) -> T;

    /// Converts to `BoxStatefulSupplier`.
    ///
    /// This method has a default implementation that wraps the
    /// supplier in a `BoxStatefulSupplier`. Custom implementations can
    /// override this for more efficient conversions.
    ///
    /// # Returns
    ///
    /// A new `BoxStatefulSupplier<T>` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, SupplierOnce};
    ///
    /// let closure = || 42;
    /// let mut boxed = StatefulSupplier::into_box(closure);
    /// assert_eq!(boxed.get(), 42);
    /// ```
    fn into_box(mut self) -> BoxStatefulSupplier<T>
    where
        Self: Sized + 'static,
    {
        BoxStatefulSupplier::new(move || self.get())
    }

    /// Converts to `RcStatefulSupplier`.
    ///
    /// This method has a default implementation that wraps the
    /// supplier in an `RcStatefulSupplier`. Custom implementations can
    /// override this for more efficient conversions.
    ///
    /// # Returns
    ///
    /// A new `RcStatefulSupplier<T>` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, SupplierOnce};
    ///
    /// let closure = || 42;
    /// let mut rc = closure.into_rc();
    /// assert_eq!(rc.get(), 42);
    /// ```
    fn into_rc(mut self) -> RcStatefulSupplier<T>
    where
        Self: Sized + 'static,
    {
        RcStatefulSupplier::new(move || self.get())
    }

    /// Converts to `ArcStatefulSupplier`.
    ///
    /// This method has a default implementation that wraps the
    /// supplier in an `ArcStatefulSupplier`. Custom implementations can
    /// override this for more efficient conversions.
    ///
    /// # Returns
    ///
    /// A new `ArcStatefulSupplier<T>` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, SupplierOnce};
    ///
    /// let closure = || 42;
    /// let mut arc = closure.into_arc();
    /// assert_eq!(arc.get(), 42);
    /// ```
    fn into_arc(mut self) -> ArcStatefulSupplier<T>
    where
        Self: Sized + Send + 'static,
    {
        ArcStatefulSupplier::new(move || self.get())
    }

    /// Converts to a closure `FnMut() -> T`.
    ///
    /// This method wraps the supplier in a closure that calls the
    /// `get()` method when invoked. This allows using suppliers
    /// in contexts that expect `FnMut()` closures.
    ///
    /// # Returns
    ///
    /// A closure `impl FnMut() -> T`
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
    ///
    /// let supplier = BoxStatefulSupplier::new(|| 42);
    /// let mut closure = supplier.into_fn();
    /// assert_eq!(closure(), 42);
    /// assert_eq!(closure(), 42);
    /// ```
    ///
    /// ## Using with functions that expect FnMut
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, BoxStatefulSupplier};
    ///
    /// fn call_fn_twice<F: FnMut() -> i32>(mut f: F) -> (i32, i32) {
    ///     (f(), f())
    /// }
    ///
    /// let supplier = BoxStatefulSupplier::new(|| 100);
    /// let closure = supplier.into_fn();
    /// assert_eq!(call_fn_twice(closure), (100, 100));
    /// ```
    fn into_fn(mut self) -> impl FnMut() -> T
    where
        Self: Sized + 'static,
    {
        move || self.get()
    }

    /// Converts to `BoxSupplierOnce`.
    ///
    /// This method has a default implementation that wraps the
    /// supplier in a `BoxSupplierOnce`. Custom implementations
    /// can override this method for optimization purposes.
    ///
    /// # Returns
    ///
    /// A new `BoxSupplierOnce<T>` instance
    ///
    /// # Examples
    ///
    /// ```rust
    /// use qubit_function::{StatefulSupplier, SupplierOnce};
    ///
    /// let closure = || 42;
    /// let once = closure.into_once();
    /// assert_eq!(once.get(), 42);
    /// ```
    fn into_once(mut self) -> BoxSupplierOnce<T>
    where
        Self: Sized + 'static,
    {
        BoxSupplierOnce::new(move || self.get())
    }

    /// Creates a `BoxStatefulSupplier` from a cloned supplier.
    ///
    /// Uses `Clone` to obtain an owned copy and converts it into a
    /// `BoxStatefulSupplier`. Implementations can override this for a more
    /// efficient conversion.
    fn to_box(&self) -> BoxStatefulSupplier<T>
    where
        Self: Clone + Sized + 'static,
    {
        self.clone().into_box()
    }

    /// Creates an `RcStatefulSupplier` from a cloned supplier.
    ///
    /// Uses `Clone` to obtain an owned copy and converts it into an
    /// `RcStatefulSupplier`. Implementations can override it for better
    /// performance.
    fn to_rc(&self) -> RcStatefulSupplier<T>
    where
        Self: Clone + Sized + 'static,
    {
        self.clone().into_rc()
    }

    /// Creates an `ArcStatefulSupplier` from a cloned supplier.
    ///
    /// Requires the supplier and produced values to be `Send` so the
    /// resulting supplier can be shared across threads.
    fn to_arc(&self) -> ArcStatefulSupplier<T>
    where
        Self: Clone + Sized + Send + 'static,
    {
        self.clone().into_arc()
    }

    /// Creates a closure from a cloned supplier.
    ///
    /// The default implementation clones `self` and consumes the clone
    /// to produce a closure. Concrete suppliers can override it to
    /// avoid the additional clone.
    fn to_fn(&self) -> impl FnMut() -> T
    where
        Self: Clone + Sized + 'static,
    {
        self.clone().into_fn()
    }

    /// Creates a `BoxSupplierOnce` from a cloned supplier
    ///
    /// Uses `Clone` to obtain an owned copy and converts it into a
    /// `BoxSupplierOnce`. Requires `Self: Clone`. Custom implementations
    /// can override this for better performance.
    fn to_once(&self) -> BoxSupplierOnce<T>
    where
        Self: Clone + Sized + 'static,
    {
        self.clone().into_once()
    }
}