qubit-function 0.8.1

Common functional programming type aliases for Rust, providing Java-style 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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/

//! Unit tests for MutatingFunctionOnce types (one-time FnOnce(&mut T) -> R)

use qubit_function::{
    BoxMutatingFunctionOnce,
    FnMutatingFunctionOnceOps,
    MutatingFunctionOnce,
};

// ============================================================================
// MutatingFunctionOnce Default Implementation Tests
// ============================================================================

/// Test struct that implements MutatingFunctionOnce to test default methods
#[derive(Clone)]
struct TestMutatingFunctionOnce {
    multiplier: i32,
}

impl TestMutatingFunctionOnce {
    fn new(multiplier: i32) -> Self {
        TestMutatingFunctionOnce { multiplier }
    }
}

impl MutatingFunctionOnce<i32, i32> for TestMutatingFunctionOnce {
    fn apply(self, input: &mut i32) -> i32 {
        let old_value = *input;
        *input *= self.multiplier;
        old_value
    }
}

#[cfg(test)]
mod test_mutating_function_once_default_impl {
    use super::*;

    #[test]
    fn test_into_box() {
        let func = TestMutatingFunctionOnce::new(2);
        let boxed = func.into_box();

        let mut value = 5;
        assert_eq!(boxed.apply(&mut value), 5);
        assert_eq!(value, 10);
    }

    #[test]
    fn test_into_fn() {
        let func = TestMutatingFunctionOnce::new(3);
        let closure = func.into_fn();

        let mut value = 4;
        assert_eq!(closure(&mut value), 4);
        assert_eq!(value, 12);
    }

    #[test]
    fn test_to_box() {
        let func = TestMutatingFunctionOnce::new(2);
        let boxed = func.to_box();

        let mut value = 5;
        assert_eq!(boxed.apply(&mut value), 5);
        assert_eq!(value, 10);
    }

    #[test]
    fn test_to_fn() {
        let func = TestMutatingFunctionOnce::new(3);
        let closure = func.to_fn();

        let mut value = 4;
        assert_eq!(closure(&mut value), 4);
        assert_eq!(value, 12);
    }
}

// ============================================================================
// BoxMutatingFunctionOnce Tests
// ============================================================================

#[cfg(test)]
mod test_box_mutating_function_once {
    use super::*;

    #[test]
    fn test_new() {
        let data = vec![1, 2, 3];
        let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        });

        let mut target = vec![0];
        let old_len = func.apply(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_new_allows_non_static_t() {
        fn run<'a>(value: &'a str) -> usize {
            let func: BoxMutatingFunctionOnce<&'a str, usize> =
                BoxMutatingFunctionOnce::new(|x: &mut &'a str| x.len());
            let mut input = value;
            func.apply(&mut input)
        }

        let text = String::from("hello");
        assert_eq!(run(text.as_str()), 5);
    }

    #[test]
    fn test_new_allows_non_static_r() {
        fn run<'a>(value: &'a str) -> &'a str {
            let func: BoxMutatingFunctionOnce<&'a str, &'a str> =
                BoxMutatingFunctionOnce::new(|x: &mut &'a str| *x);
            let mut input = value;
            func.apply(&mut input)
        }

        let text = String::from("qubit");
        assert_eq!(run(text.as_str()), "qubit");
    }

    #[test]
    fn test_with_string() {
        let data = String::from(" world");
        let func = BoxMutatingFunctionOnce::new(move |x: &mut String| {
            let old_len = x.len();
            x.push_str(&data);
            old_len
        });

        let mut target = String::from("hello");
        let old_len = func.apply(&mut target);
        assert_eq!(old_len, 5);
        assert_eq!(target, "hello world");
    }

    #[test]
    fn test_and_then() {
        let data1 = vec![1, 2];
        let data2 = [3, 4];

        let chained = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            x.extend(data1);
            x.len()
        })
        .and_then(move |len: &usize| {
            // First function returned the length, now we can use it
            *len + data2.len()
        });

        let mut target = vec![0];
        let final_len = chained.apply(&mut target);
        assert_eq!(final_len, 5); // 3 (target.len() after extend) + 2 (data2.len())
        assert_eq!(target, vec![0, 1, 2]);
    }

    #[test]
    fn test_and_then_multiple_chains() {
        let data1 = vec![1, 2];
        let data2 = [3, 4];
        let data3 = [5, 6];

        let chained = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            x.extend(data1);
            x.len()
        })
        .and_then(move |len: &usize| {
            // First chain: add data2 length to current length
            *len + data2.len()
        })
        .and_then(move |len: &usize| {
            // Second chain: add data3 length to current length
            *len + data3.len()
        });

        let mut target = vec![0];
        let final_len = chained.apply(&mut target);
        assert_eq!(final_len, 7); // 3 (initial len) + 2 (data2) + 2 (data3)
        assert_eq!(target, vec![0, 1, 2]);
    }

    #[test]
    fn test_identity() {
        let identity = BoxMutatingFunctionOnce::<i32, i32>::identity();
        let mut value = 42;
        let result = identity.apply(&mut value);
        assert_eq!(result, 42);
        assert_eq!(value, 42);
    }

    #[test]
    fn test_map() {
        let data = vec![1, 2, 3];
        let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        });
        let mapped =
            func.and_then::<String, _>(|old_len: &usize| format!("Old length: {}", *old_len));

        let mut target = vec![0];
        let result = mapped.apply(&mut target);
        assert_eq!(result, "Old length: 1");
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_validation_pattern() {
        struct Data {
            value: i32,
        }

        let validator = BoxMutatingFunctionOnce::new(|data: &mut Data| {
            if data.value < 0 {
                data.value = 0;
                Err("Fixed negative value")
            } else {
                Ok("Valid")
            }
        });

        let mut data = Data { value: -5 };
        let result = validator.apply(&mut data);
        assert_eq!(data.value, 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_resource_transfer() {
        let resource = vec![1, 2, 3, 4, 5];
        let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            let old_sum: i32 = x.iter().sum();
            x.extend(resource);
            old_sum
        });

        let mut target = vec![10, 20];
        let old_sum = func.apply(&mut target);
        assert_eq!(old_sum, 30);
        assert_eq!(target, vec![10, 20, 1, 2, 3, 4, 5]);
    }
}

// ============================================================================
// Closure Tests
// ============================================================================

#[cfg(test)]
mod test_closure {
    use super::*;

    #[test]
    fn test_closure_implements_trait() {
        let data = vec![1, 2, 3];
        let closure = move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        };

        let mut target = vec![0];
        let old_len = closure.apply(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_closure_and_then() {
        let data1 = vec![1, 2];
        let data2 = [3, 4];

        let chained = (move |x: &mut Vec<i32>| {
            x.extend(data1);
            x.len() // returns usize
        })
        .and_then(move |len: &usize| {
            // Calculate based on the length returned by the previous function
            *len + data2.len()
        });

        let mut target = vec![0];
        let final_len = chained.apply(&mut target);
        assert_eq!(final_len, 5); // 2 (from data1) + 2 (data2.len()) + 1 (original len)
        assert_eq!(target, vec![0, 1, 2]);
    }

    #[test]
    fn test_closure_map() {
        let data = vec![1, 2, 3];
        let mapped = (move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        })
        .and_then::<String, _>(|old_len: &usize| format!("Old length: {}", *old_len));

        let mut target = vec![0];
        let result = mapped.apply(&mut target);
        assert_eq!(result, "Old length: 1");
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_closure_into_box() {
        let data = vec![1, 2, 3];
        let closure = move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        };
        let box_func = closure.into_box();

        let mut target = vec![0];
        let old_len = box_func.apply(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_closure_into_fn() {
        let data = vec![1, 2, 3];
        let closure = move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        };
        let fn_closure = closure.into_fn();

        let mut target = vec![0];
        let old_len = fn_closure(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_closure_to_box() {
        let data = vec![1, 2, 3];
        let closure = move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        };
        let box_func = closure.to_box();

        let mut target = vec![0];
        let old_len = box_func.apply(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_closure_to_fn() {
        let data = vec![1, 2, 3];
        let closure = move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        };
        let fn_closure = closure.to_fn();

        let mut target = vec![0];
        let old_len = fn_closure(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_move_semantics() {
        let data = vec![1, 2, 3];
        let closure = move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data); // data is moved into closure
            old_len
        };
        // data is no longer accessible here

        let mut target = vec![0];
        let old_len = closure.apply(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_into_box() {
        let data = vec![1, 2, 3];
        let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        });

        let box_func = func.into_box();

        let mut target = vec![0];
        let old_len = box_func.apply(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }

    #[test]
    fn test_into_fn() {
        let data = vec![1, 2, 3];
        let func = BoxMutatingFunctionOnce::new(move |x: &mut Vec<i32>| {
            let old_len = x.len();
            x.extend(data);
            old_len
        });

        let closure = func.into_fn();

        let mut target = vec![0];
        let old_len = closure(&mut target);
        assert_eq!(old_len, 1);
        assert_eq!(target, vec![0, 1, 2, 3]);
    }
}

// ============================================================================
// MutatingFunctionOnce Debug and Display Tests
// ============================================================================

#[test]
fn test_box_mutating_function_once_debug_display() {
    // Test Debug and Display for BoxMutatingFunctionOnce without name
    let double = BoxMutatingFunctionOnce::new(|x: &mut i32| *x * 2);
    let debug_str = format!("{:?}", double);
    assert!(debug_str.contains("BoxMutatingFunctionOnce"));
    assert!(debug_str.contains("name"));
    assert!(debug_str.contains("function"));

    let display_str = format!("{}", double);
    assert_eq!(display_str, "BoxMutatingFunctionOnce");

    // Test Debug and Display for BoxMutatingFunctionOnce with name
    let named_double =
        BoxMutatingFunctionOnce::new_with_name("mutating_once_double", |x: &mut i32| *x * 2);
    let named_debug_str = format!("{:?}", named_double);
    assert!(named_debug_str.contains("BoxMutatingFunctionOnce"));
    assert!(named_debug_str.contains("name"));
    assert!(named_debug_str.contains("function"));

    let named_display_str = format!("{}", named_double);
    assert_eq!(
        named_display_str,
        "BoxMutatingFunctionOnce(mutating_once_double)"
    );
}

// ============================================================================
// MutatingFunctionOnce Name Management Tests
// ============================================================================

#[test]
fn test_box_mutating_function_once_name_methods() {
    // Test new_with_name, name(), and set_name()
    let mut double =
        BoxMutatingFunctionOnce::new_with_name("box_mutating_once_func", |x: &mut i32| {
            *x *= 2;
            *x
        });

    // Test name() returns the initial name
    assert_eq!(double.name(), Some("box_mutating_once_func"));

    // Test set_name() changes the name
    double.set_name("modified_box_mutating_once");
    assert_eq!(double.name(), Some("modified_box_mutating_once"));

    // Test that function still works after name change
    let mut value = 5;
    assert_eq!(double.apply(&mut value), 10);
    assert_eq!(value, 10);
}

// ============================================================================
// ConditionalMutatingFunctionOnce Debug and Display Tests
// ============================================================================

#[test]
fn test_box_conditional_mutating_function_once_debug_display() {
    // Test Debug and Display for BoxConditionalMutatingFunctionOnce without name
    let double = BoxMutatingFunctionOnce::new(|x: &mut i32| *x * 2);
    let conditional = double.when(|x: &i32| *x > 0);

    let debug_str = format!("{:?}", conditional);
    assert!(debug_str.contains("BoxConditionalMutatingFunctionOnce"));
    assert!(debug_str.contains("name"));
    assert!(debug_str.contains("function"));
    assert!(debug_str.contains("predicate"));

    let display_str = format!("{}", conditional);
    assert!(display_str.starts_with("BoxConditionalMutatingFunctionOnce("));
    assert!(display_str.contains("BoxMutatingFunctionOnce"));
    assert!(display_str.contains("BoxPredicate"));
    assert!(display_str.ends_with(")"));

    // Test Debug and Display for BoxConditionalMutatingFunctionOnce with name
    let triple =
        BoxMutatingFunctionOnce::new_with_name("triple_mutating_once_func", |x: &mut i32| *x * 3);
    let named_conditional = triple.when(|x: &i32| *x % 2 == 0);

    let named_debug_str = format!("{:?}", named_conditional);
    assert!(named_debug_str.contains("BoxConditionalMutatingFunctionOnce"));
    assert!(named_debug_str.contains("name"));
    assert!(named_debug_str.contains("function"));
    assert!(named_debug_str.contains("predicate"));

    let named_display_str = format!("{}", named_conditional);
    assert!(named_display_str.starts_with("BoxConditionalMutatingFunctionOnce("));
    assert!(named_display_str.contains("BoxMutatingFunctionOnce(triple_mutating_once_func)"));
    assert!(named_display_str.contains("BoxPredicate"));
    assert!(named_display_str.ends_with(")"));
}

#[test]
fn test_custom_cloneable_mutating_function_once_to_box() {
    // Test to_box method on a custom struct that implements both MutatingFunctionOnce and Clone
    #[derive(Clone, Debug)]
    struct MyCloneableMutatingFunction {
        multiplier: i32,
        offset: i32,
    }

    impl MyCloneableMutatingFunction {
        fn new(multiplier: i32, offset: i32) -> Self {
            Self { multiplier, offset }
        }
    }

    impl MutatingFunctionOnce<i32, i32> for MyCloneableMutatingFunction {
        fn apply(self, input: &mut i32) -> i32 {
            *input = *input * self.multiplier + self.offset;
            *input
        }
    }

    // Test that to_box method is available and works correctly
    let func = MyCloneableMutatingFunction::new(2, 5);

    // Use to_box method (should be available because struct implements Clone)
    let mut input1 = 3;
    let boxed = func.to_box();
    let result1 = boxed.apply(&mut input1);
    assert_eq!(result1, 11); // (3 * 2) + 5 = 11
    assert_eq!(input1, 11);

    // Original function should still be usable (because to_box borrows &self)
    let mut input2 = 4;
    let another_boxed = func.to_box();
    let result2 = another_boxed.apply(&mut input2);
    assert_eq!(result2, 13); // (4 * 2) + 5 = 13
    assert_eq!(input2, 13);

    // Test to_fn method as well
    let func_closure = func.to_fn();
    let mut input3 = 2;
    let result3 = func_closure(&mut input3);
    assert_eq!(result3, 9); // (2 * 2) + 5 = 9
    assert_eq!(input3, 9);

    // Original function should still be usable after to_fn
    let mut input4 = 1;
    let final_boxed = func.to_box();
    let result4 = final_boxed.apply(&mut input4);
    assert_eq!(result4, 7); // (1 * 2) + 5 = 7
    assert_eq!(input4, 7);
}