thread_aware 0.7.3

Facilities to support thread-isolated state.
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Helpers for defining and calling [`ThreadAware`] closures.

mod erased;

use std::pin::Pin;

pub(crate) use erased::ErasedClosureOnce;

use crate::ThreadAware;
use crate::affinity::Affinity;

/// A boxed, pinned, `Send` future - the return type of async closure calls.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Marks `FnOnce()`-like closures whose captured values all implement [`ThreadAware`].
///
/// Use [`closure_once`] function to construct these.
pub trait ThreadAwareFnOnce<T: ?Sized>: ThreadAware {
    /// Calls the closure, consuming it in the process.
    fn call_once(self) -> T;
}

/// Marks `Fn()`-like closure whose captured values all implement [`ThreadAware`].
///
/// This trait is used to define closures that can be called multiple times, without consuming the closure.
pub trait ThreadAwareFn<T>: ThreadAware {
    /// Calls the closure, returning the result.
    fn call(&self) -> T;
}

/// Marks `FnMut()`-like closure whose captured values all implement [`ThreadAware`].
///
/// This trait is used to define closures that can be called mutably, allowing the closure to modify its internal state.
pub trait ThreadAwareFnMut<T>: ThreadAware {
    /// Calls the closure mutably, returning the result.
    fn call_mut(&mut self) -> T;
}

/// Async equivalent of [`ThreadAwareFnOnce`] - calls the closure once, returning a [`BoxFuture`].
///
/// Use [`async_closure_once`] to construct an implementation.
pub trait ThreadAwareAsyncFnOnce<T>: ThreadAware {
    /// Calls the async closure, consuming it.
    fn call_once(self: Box<Self>) -> BoxFuture<'static, T>;
}

/// Async equivalent of [`ThreadAwareFn`] - calls the closure by shared reference, returning a [`BoxFuture`].
///
/// Use [`async_closure`] to construct an implementation.
pub trait ThreadAwareAsyncFn<T>: ThreadAware {
    /// Calls the async closure by shared reference.
    fn call(&self) -> BoxFuture<'_, T>;
}

/// Async equivalent of [`ThreadAwareFnMut`] - calls the closure by mutable reference, returning a [`BoxFuture`].
///
/// Use [`async_closure_mut`] to construct an implementation.
pub trait ThreadAwareAsyncFnMut<T>: ThreadAware {
    /// Calls the async closure by mutable reference.
    fn call_mut(&mut self) -> BoxFuture<'_, T>;
}

/// A common implementation of [`ThreadAwareFn`].
///
/// Construct this using the [`closure`] function.
#[derive(Debug, Copy, Hash)]
pub struct Closure<T, D> {
    data: D,
    f: fn(&D) -> T,
}

impl<T, D> Clone for Closure<T, D>
where
    D: Clone,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            f: self.f,
        }
    }
}

impl<T, D> ThreadAwareFn<T> for Closure<T, D>
where
    D: ThreadAware,
{
    fn call(&self) -> T {
        (self.f)(&self.data)
    }
}

impl<T, D> ThreadAwareFnMut<T> for Closure<T, D>
where
    D: ThreadAware,
{
    fn call_mut(&mut self) -> T {
        self.call()
    }
}

impl<T, D> ThreadAwareFnOnce<T> for Closure<T, D>
where
    D: ThreadAware,
{
    fn call_once(self) -> T {
        self.call()
    }
}

impl<T, D> ThreadAware for Closure<T, D>
where
    D: ThreadAware,
{
    fn relocate(&mut self, source: Option<Affinity>, destination: Affinity) {
        self.data.relocate(source, destination);
    }
}

/// A common implementation of [`ThreadAwareFnOnce`].
///
/// Construct this using the [`closure_once`] function.
#[derive(Debug, Copy, Hash)]
pub struct ClosureOnce<T, D> {
    data: D,
    f: fn(D) -> T,
}

impl<T, D> Clone for ClosureOnce<T, D>
where
    D: Clone,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            f: self.f,
        }
    }
}

impl<T, D> ThreadAwareFnOnce<T> for ClosureOnce<T, D>
where
    D: ThreadAware,
{
    fn call_once(self) -> T {
        (self.f)(self.data)
    }
}

impl<T, D> ThreadAware for ClosureOnce<T, D>
where
    D: ThreadAware,
{
    fn relocate(&mut self, source: Option<Affinity>, destination: Affinity) {
        self.data.relocate(source, destination);
    }
}

/// A common implementation of [`ThreadAwareFnMut`].
///
/// Construct this using the [`closure_mut`] function.
#[derive(Debug, Copy, Hash)]
pub struct ClosureMut<T, D> {
    data: D,
    f: fn(&mut D) -> T,
}

impl<T, D> Clone for ClosureMut<T, D>
where
    D: Clone,
{
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            f: self.f,
        }
    }
}

impl<T, D> ThreadAwareFnMut<T> for ClosureMut<T, D>
where
    D: ThreadAware,
{
    fn call_mut(&mut self) -> T {
        (self.f)(&mut self.data)
    }
}

impl<T, D> ThreadAwareFnOnce<T> for ClosureMut<T, D>
where
    D: ThreadAware,
{
    fn call_once(mut self) -> T {
        self.call_mut()
    }
}

impl<T, D> ThreadAware for ClosureMut<T, D>
where
    D: ThreadAware,
{
    fn relocate(&mut self, source: Option<Affinity>, destination: Affinity) {
        self.data.relocate(source, destination);
    }
}

/// Constructs a [`Closure`].
///
/// Create a closure-like object by explicitly providing closed-over
/// value and a function pointer to operate on that value, essentially simulating a
/// parameterless closure that ensures that captured data implements [`ThreadAware`].
pub fn closure<T, D>(data: D, f: fn(&D) -> T) -> Closure<T, D>
where
    D: ThreadAware,
{
    Closure { data, f }
}

/// Constructs a [`ClosureMut`].
///
/// Create a closure-like object by explicitly providing closed-over
/// value and a function pointer to operate on that value, essentially simulating a
/// parameterless closure that ensures that captured data implements [`ThreadAware`].
pub fn closure_mut<T, D>(data: D, f: fn(&mut D) -> T) -> ClosureMut<T, D>
where
    D: ThreadAware,
{
    ClosureMut { data, f }
}

/// Constructs a [`ClosureOnce`].
///
/// Create a closure-like object by explicitly providing closed-over
/// value and a function pointer to operate on that value, essentially simulating a
/// parameterless closure that ensures that captured data implements [`ThreadAware`].
///
/// Usage:
/// ```rust
/// # use thread_aware::{ThreadAware, closure::closure_once, closure::ThreadAwareFnOnce};
/// # use thread_aware::affinity::*;
/// struct Transferable;
/// impl ThreadAware for Transferable {
///     // ...
///     # fn relocate(&mut self, _source: Option<Affinity>, _destination: Affinity) {}
/// }
///
/// let closure = closure_once(Transferable, |transferable| {
///     // do stuff with transferable
/// });
///
/// closure.call_once();
///
/// let closure_with_multiple_captured = closure_once((Transferable, Transferable), |(a, b)| {
///     // do stuff with a and b
/// });
///
/// closure_with_multiple_captured.call_once();
/// ```
///
/// This exists because Rust closures don't give us control over the types of captured values.
pub fn closure_once<T, D>(data: D, f: fn(D) -> T) -> ClosureOnce<T, D>
where
    D: ThreadAware,
{
    ClosureOnce { data, f }
}

// --- Async closure types ---

/// Async equivalent of [`Closure`] - can be called multiple times by shared reference.
///
/// The function pointer receives `&D` and must return a [`BoxFuture`].
/// Construct this using the [`async_closure`] function.
#[derive(Copy)]
pub struct AsyncClosure<T, D> {
    data: D,
    f: for<'a> fn(&'a D) -> BoxFuture<'a, T>,
}

impl<T, D: std::fmt::Debug> std::fmt::Debug for AsyncClosure<T, D> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncClosure").field("data", &self.data).finish_non_exhaustive()
    }
}

impl<T, D: Clone> Clone for AsyncClosure<T, D> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            f: self.f,
        }
    }
}

impl<T, D: ThreadAware> AsyncClosure<T, D> {
    /// Calls the async closure by shared reference.
    pub fn call(&self) -> BoxFuture<'_, T> {
        (self.f)(&self.data)
    }
}

impl<T, D: ThreadAware> ThreadAwareAsyncFn<T> for AsyncClosure<T, D> {
    fn call(&self) -> BoxFuture<'_, T> {
        self.call()
    }
}

impl<T, D: ThreadAware> ThreadAwareAsyncFnMut<T> for AsyncClosure<T, D> {
    fn call_mut(&mut self) -> BoxFuture<'_, T> {
        self.call()
    }
}

impl<T, D: ThreadAware + 'static> ThreadAwareAsyncFnOnce<T> for AsyncClosure<T, D>
where
    T: 'static,
{
    fn call_once(self: Box<Self>) -> BoxFuture<'static, T> {
        Box::pin(async move { self.call().await })
    }
}

impl<T, D: ThreadAware> ThreadAware for AsyncClosure<T, D> {
    fn relocate(&mut self, source: Option<Affinity>, destination: Affinity) {
        self.data.relocate(source, destination);
    }
}

/// Async equivalent of [`ClosureOnce`] - can be called exactly once, consuming `self`.
///
/// The function pointer receives owned `D` and must return a [`BoxFuture`].
/// Construct this using the [`async_closure_once`] function.
#[derive(Copy)]
pub struct AsyncClosureOnce<T, D> {
    data: D,
    f: fn(D) -> BoxFuture<'static, T>,
}

impl<T, D: std::fmt::Debug> std::fmt::Debug for AsyncClosureOnce<T, D> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncClosureOnce").field("data", &self.data).finish_non_exhaustive()
    }
}

impl<T, D: Clone> Clone for AsyncClosureOnce<T, D> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            f: self.f,
        }
    }
}

impl<T, D: ThreadAware> AsyncClosureOnce<T, D> {
    /// Calls the async closure, consuming it.
    pub fn call_once(self) -> BoxFuture<'static, T> {
        (self.f)(self.data)
    }
}

impl<T, D: ThreadAware> ThreadAwareAsyncFnOnce<T> for AsyncClosureOnce<T, D> {
    fn call_once(self: Box<Self>) -> BoxFuture<'static, T> {
        (self.f)(self.data)
    }
}

impl<T, D: ThreadAware> ThreadAware for AsyncClosureOnce<T, D> {
    fn relocate(&mut self, source: Option<Affinity>, destination: Affinity) {
        self.data.relocate(source, destination);
    }
}

/// Async equivalent of [`ClosureMut`] - can be called multiple times by mutable reference.
///
/// The function pointer receives `&mut D` and must return a [`BoxFuture`].
/// Construct this using the [`async_closure_mut`] function.
#[derive(Copy)]
pub struct AsyncClosureMut<T, D> {
    data: D,
    f: for<'a> fn(&'a mut D) -> BoxFuture<'a, T>,
}

impl<T, D: std::fmt::Debug> std::fmt::Debug for AsyncClosureMut<T, D> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AsyncClosureMut").field("data", &self.data).finish_non_exhaustive()
    }
}

impl<T, D: Clone> Clone for AsyncClosureMut<T, D> {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            f: self.f,
        }
    }
}

impl<T, D: ThreadAware> AsyncClosureMut<T, D> {
    /// Calls the async closure by mutable reference.
    pub fn call_mut(&mut self) -> BoxFuture<'_, T> {
        (self.f)(&mut self.data)
    }
}

impl<T, D: ThreadAware> ThreadAwareAsyncFnMut<T> for AsyncClosureMut<T, D> {
    fn call_mut(&mut self) -> BoxFuture<'_, T> {
        self.call_mut()
    }
}

impl<T, D: ThreadAware + 'static> ThreadAwareAsyncFnOnce<T> for AsyncClosureMut<T, D>
where
    T: 'static,
{
    fn call_once(mut self: Box<Self>) -> BoxFuture<'static, T> {
        Box::pin(async move { self.call_mut().await })
    }
}

impl<T, D: ThreadAware> ThreadAware for AsyncClosureMut<T, D> {
    fn relocate(&mut self, source: Option<Affinity>, destination: Affinity) {
        self.data.relocate(source, destination);
    }
}

/// Constructs an [`AsyncClosure`] - the async equivalent of [`closure`].
///
/// The function pointer receives `&D` and must return a [`BoxFuture`].
/// Use `Box::pin(async move { ... })` in the function body.
///
/// # Examples
///
/// ```rust
/// use thread_aware::closure::async_closure;
///
/// fn my_async_fn(x: &i32) -> thread_aware::closure::BoxFuture<'_, i32> {
///     Box::pin(async move { *x + 1 })
/// }
///
/// let c = async_closure(42, my_async_fn);
/// ```
pub fn async_closure<T, D>(data: D, f: for<'a> fn(&'a D) -> BoxFuture<'a, T>) -> AsyncClosure<T, D>
where
    D: ThreadAware,
{
    AsyncClosure { data, f }
}

/// Constructs an [`AsyncClosureMut`] - the async equivalent of [`closure_mut`].
///
/// The function pointer receives `&mut D` and must return a [`BoxFuture`].
/// Use `Box::pin(async move { ... })` in the function body.
pub fn async_closure_mut<T, D>(data: D, f: for<'a> fn(&'a mut D) -> BoxFuture<'a, T>) -> AsyncClosureMut<T, D>
where
    D: ThreadAware,
{
    AsyncClosureMut { data, f }
}

/// Constructs an [`AsyncClosureOnce`] - the async equivalent of [`closure_once`].
///
/// The function pointer receives owned `D` and must return a [`BoxFuture`].
/// Use `Box::pin(async move { ... })` in the function body.
pub fn async_closure_once<T, D>(data: D, f: fn(D) -> BoxFuture<'static, T>) -> AsyncClosureOnce<T, D>
where
    D: ThreadAware,
{
    AsyncClosureOnce { data, f }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::affinity::pinned_affinities;

    #[test]
    fn async_closure_once_compiles() {
        let c = async_closure_once(42, |x| Box::pin(async move { x + 1 }));
        let fut = c.call_once();
        let result = futures::executor::block_on(fut);
        assert_eq!(result, 43);
    }

    #[test]
    fn async_closure_compiles() {
        let c = async_closure(42, |x| Box::pin(async move { *x + 1 }));
        let result = futures::executor::block_on(c.call());
        assert_eq!(result, 43);
    }

    #[test]
    fn async_closure_mut_compiles() {
        fn increment(x: &mut i32) -> BoxFuture<'_, i32> {
            *x += 1;
            let val = *x;
            Box::pin(async move { val })
        }

        let mut c = async_closure_mut(0_i32, increment);
        let r1 = futures::executor::block_on(c.call_mut());
        let r2 = futures::executor::block_on(c.call_mut());
        assert_eq!(r1, 1);
        assert_eq!(r2, 2);
    }

    #[test]
    fn boxed_once() {
        let x = closure_once(42, |x| x + 1);
        let y = Box::new(x);
        let _z = y.call_once();
    }

    #[test]
    fn more_stuff() {
        let x = Closure { data: 42, f: |x| x + 1 };

        let _y = x.call();
    }

    #[test]
    fn something() {
        fn takes_mut(mut x: impl ThreadAwareFnMut<i32>) {
            let _y = x.call_mut();
        }

        let x = closure(42, |x| x + 1);
        takes_mut(x);
    }

    #[expect(clippy::empty_structs_with_brackets, reason = " Testing non-clone behavior")]
    #[test]
    fn non_clone() {
        struct MyStruct {}

        let y = closure((), |()| MyStruct {});
        let _z = y.call();
    }

    #[expect(clippy::redundant_clone, reason = "Testing clone behavior")]
    #[test]
    fn can_clone() {
        let x = Closure {
            data: String::from("Hello, world!"),
            f: |_| 43,
        };

        assert_eq!(x.call(), 43);
        let y = x.clone();
        assert_eq!(y.call(), 43);
    }

    // Tests for Closure<T, D>

    #[test]
    fn test_closure_clone() {
        // Test with Vec
        let c = closure(vec![1, 2, 3], std::vec::Vec::len);
        let cloned = c.clone();
        assert_eq!(c.call(), 3);
        assert_eq!(cloned.call(), 3);

        // Test with String
        let c = Closure {
            data: String::from("test"),
            f: |s| s.len(),
        };

        let cloned = c.clone();
        assert_eq!(c.call(), 4);
        assert_eq!(cloned.call(), 4);
    }

    #[test]
    fn test_closure_thread_aware() {
        let affinities = pinned_affinities(&[2, 2]);

        // Test with i32
        let mut c = closure(42_i32, |x| x + 1);
        c.relocate(Some(affinities[0]), affinities[1]);
        assert_eq!(c.call(), 43);

        // Test with Vec
        let mut c = closure(vec![10, 20, 30], |v| v.iter().sum::<i32>());
        c.relocate(Some(affinities[0]), affinities[2]);
        assert_eq!(c.call(), 60);

        // Test with same affinity (String)
        let mut c = closure(String::from("hello"), |s| s.to_uppercase());
        c.relocate(Some(affinities[0]), affinities[0]);
        assert_eq!(c.call(), "HELLO");
    }

    #[test]
    fn test_closure_thread_aware_fn_mut() {
        // Test with i32 - multiple calls should give same result
        let mut c = closure(5_i32, |x| x * 2);
        assert_eq!(c.call_mut(), 10);
        assert_eq!(c.call_mut(), 10);

        // Test with Vec - multiple calls should give same result
        let mut c = closure(vec![1, 2, 3, 4], std::vec::Vec::len);

        assert_eq!(c.call_mut(), 4);
        assert_eq!(c.call_mut(), 4);
        assert_eq!(c.call_mut(), 4);
    }

    // Tests for ClosureOnce<T, D>

    #[test]
    fn test_closure_once_clone() {
        // Test with i32
        let closure = closure_once(100_i32, |x| x * 2);
        let cloned = closure;
        assert_eq!(closure.call_once(), 200);
        assert_eq!(cloned.call_once(), 200);

        // Test with complex data (tuple)
        let closure = ClosureOnce {
            data: (String::from("test"), vec![1, 2, 3]),
            f: |(s, v)| format!("{}: {}", s, v.len()),
        };

        let cloned = closure.clone();
        assert_eq!(closure.call_once(), "test: 3");
        assert_eq!(cloned.call_once(), "test: 3");
    }

    #[test]
    fn test_closure_once_thread_aware() {
        let affinities = pinned_affinities(&[2, 3]);

        // Test with String
        let mut closure = closure_once(String::from("world"), |s| format!("Hello, {s}!"));
        closure.relocate(Some(affinities[0]), affinities[1]);
        assert_eq!(closure.call_once(), "Hello, world!");

        // Test with complex data (tuple of Vecs)
        let data = (vec![1, 2, 3], vec![4, 5, 6]);
        let mut closure = closure_once(data, |(a, b)| a.len() + b.len());
        closure.relocate(Some(affinities[1]), affinities[3]);
        assert_eq!(closure.call_once(), 6);

        // Test cross-NUMA transfer
        let mut closure = closure_once(42_i32, |x| x + 100);
        closure.relocate(Some(affinities[0]), affinities[2]);
        assert_eq!(closure.call_once(), 142);
    }

    // Tests for ClosureMut<T, D>

    #[test]
    fn test_closure_mut_clone() {
        // Test with i32 - clone creates independent copies
        let closure = closure_mut(10_i32, |x| {
            *x += 5;
            *x
        });
        let cloned = closure;
        let mut c1 = closure;
        let mut c2 = cloned;
        assert_eq!(c1.call_mut(), 15);
        assert_eq!(c2.call_mut(), 15);

        // Test with Vec - independent copies continue to grow independently
        let closure = ClosureMut {
            data: vec![1, 2, 3],
            f: |v| {
                v.push(4);
                v.len()
            },
        };
        let cloned = closure.clone();
        let mut c1 = closure;
        let mut c2 = cloned;

        assert_eq!(c1.call_mut(), 4);
        assert_eq!(c1.call_mut(), 5); // Continues to grow
        assert_eq!(c2.call_mut(), 4); // Independent copy
    }

    #[test]
    fn test_closure_mut_thread_aware() {
        let affinities = pinned_affinities(&[2, 3]);

        // Test with i32 - mutating state across relocations
        let mut closure = closure_mut(0_i32, |x| {
            *x += 1;
            *x
        });
        closure.relocate(Some(affinities[0]), affinities[2]);
        assert_eq!(closure.call_mut(), 1);
        assert_eq!(closure.call_mut(), 2);

        // Test with String - mutating string state
        let mut closure = closure_mut(String::new(), |s| {
            s.push('x');
            s.len()
        });

        closure.relocate(Some(affinities[0]), affinities[2]);
        assert_eq!(closure.call_mut(), 1);
        assert_eq!(closure.call_mut(), 2);
        assert_eq!(closure.call_mut(), 3);
    }

    #[test]
    fn test_closure_mut_relocate_fn_mut() {
        let mut closure = closure_mut(vec![1, 2], |v| {
            v.push(v.len() + 1);
            v.len()
        });

        assert_eq!(closure.call_mut(), 3);
        assert_eq!(closure.call_mut(), 4);
        assert_eq!(closure.call_mut(), 5);
    }

    #[test]
    fn test_closure_mut_relocate_fn_mut_independent_after_clone() {
        let closure = closure_mut(0_i32, |x| {
            *x += 10;
            *x
        });

        let mut c1 = closure;
        let mut c2 = closure;

        assert_eq!(c1.call_mut(), 10);
        assert_eq!(c1.call_mut(), 20);
        assert_eq!(c2.call_mut(), 10);
        assert_eq!(c2.call_mut(), 20);
    }

    #[test]
    fn test_closure_mut_relocate_fn_once() {
        let closure = closure_mut(String::from("test"), |s| {
            s.push('!');
            s.clone()
        });

        let result = closure.call_once();
        assert_eq!(result, "test!");
    }

    // Integration tests combining traits

    #[test]
    fn test_closure_all_traits_together() {
        let affinities = pinned_affinities(&[2]);
        let c = closure(vec![1, 2, 3], std::vec::Vec::len);

        // Test Clone
        let mut cloned = c;

        // Test ThreadAware
        cloned.relocate(Some(affinities[0]), affinities[1]);

        // Test ThreadAwareFnMut
        assert_eq!(cloned.call_mut(), 3);
    }

    #[test]
    fn test_closure_mut_all_traits_together() {
        let affinities = pinned_affinities(&[2, 2]);
        let closure = closure_mut(100_i32, |x| {
            *x += 1;
            *x
        });

        // Test Clone
        let mut cloned = closure;

        // Test ThreadAware across NUMA nodes
        cloned.relocate(Some(affinities[0]), affinities[3]);

        // Test ThreadAwareFnMut
        assert_eq!(cloned.call_mut(), 101);
        assert_eq!(cloned.call_mut(), 102);
    }

    #[test]
    fn test_closure_once_with_thread_aware_and_clone() {
        let affinities = pinned_affinities(&[2]);
        let closure = closure_once((1, 2, 3), |(a, b, c)| a + b + c);

        // Test Clone
        let mut cloned = closure;

        // Test ThreadAware
        cloned.relocate(Some(affinities[0]), affinities[1]);

        // Call once
        assert_eq!(cloned.call_once(), 6);

        // Original can still be used
        assert_eq!(closure.call_once(), 6);
    }

    // ---- Mutation-detecting tests ----
    // These use a Tracker type that visibly changes on relocate, ensuring
    // mutation testing catches no-op replacements of relocate bodies.

    #[derive(Clone, Debug, PartialEq)]
    struct Tracker(bool);

    impl ThreadAware for Tracker {
        fn relocate(&mut self, _source: Option<Affinity>, _destination: Affinity) {
            self.0 = true;
        }
    }

    fn affinities() -> (Option<Affinity>, Affinity) {
        let a = pinned_affinities(&[2]);
        (Some(a[0]), a[1])
    }

    #[test]
    fn closure_relocate_forwards_to_data() {
        let (src, dst) = affinities();
        let mut c = closure(Tracker(false), |t| t.0);
        c.relocate(src, dst);
        assert!(c.call(), "Closure must forward relocate to captured data");
    }

    #[test]
    fn closure_once_relocate_forwards_to_data() {
        let (src, dst) = affinities();
        let mut c = closure_once(Tracker(false), |t| t.0);
        c.relocate(src, dst);
        assert!(c.call_once(), "ClosureOnce must forward relocate to captured data");
    }

    #[test]
    fn closure_mut_relocate_forwards_to_data() {
        let (src, dst) = affinities();
        let mut c = closure_mut(Tracker(false), |t| t.0);
        c.relocate(src, dst);
        assert!(c.call_mut(), "ClosureMut must forward relocate to captured data");
    }

    #[test]
    fn async_closure_relocate_forwards_to_data() {
        let (src, dst) = affinities();
        let mut c = async_closure(Tracker(false), |t| Box::pin(async move { t.0 }));
        c.relocate(src, dst);
        let result = futures::executor::block_on(c.call());
        assert!(result, "AsyncClosure must forward relocate to captured data");
    }

    #[test]
    fn async_closure_once_relocate_forwards_to_data() {
        let (src, dst) = affinities();
        let mut c = async_closure_once(Tracker(false), |t| Box::pin(async move { t.0 }));
        c.relocate(src, dst);
        let result = futures::executor::block_on(c.call_once());
        assert!(result, "AsyncClosureOnce must forward relocate to captured data");
    }

    #[test]
    fn async_closure_mut_relocate_forwards_to_data() {
        let (src, dst) = affinities();
        let mut c = async_closure_mut(Tracker(false), |t| {
            let val = t.0;
            Box::pin(async move { val })
        });
        c.relocate(src, dst);
        let result = futures::executor::block_on(c.call_mut());
        assert!(result, "AsyncClosureMut must forward relocate to captured data");
    }

    // ---- Coverage for Debug, Clone, call_once, trait impls on async closure types ----

    #[test]
    fn closure_call_once_trait() {
        // Exercises ThreadAwareFnOnce::call_once for Closure (line 109-111)
        let c = closure(42_i32, |x| *x + 1);
        assert_eq!(ThreadAwareFnOnce::call_once(c), 43);
    }

    #[test]
    fn async_closure_debug_and_clone() {
        let c = async_closure(String::from("hello"), |x| Box::pin(async move { x.len() }));
        let dbg = format!("{c:?}");
        assert!(dbg.contains("AsyncClosure"), "{dbg}");
        let c2 = c.clone();
        let r = futures::executor::block_on(c2.call());
        assert_eq!(r, 5);
        // Use original after clone to prove clone is not redundant
        let r2 = futures::executor::block_on(c.call());
        assert_eq!(r2, 5);
    }

    #[test]
    fn async_closure_trait_impls() {
        // ThreadAwareAsyncFn::call
        let c = async_closure(10_i32, |x| Box::pin(async move { *x }));
        let c: Box<dyn ThreadAwareAsyncFn<i32>> = Box::new(c);
        let r = futures::executor::block_on(c.call());
        assert_eq!(r, 10);

        // ThreadAwareAsyncFnMut::call_mut
        let mut c = async_closure(10_i32, |x| Box::pin(async move { *x }));
        let r = futures::executor::block_on(ThreadAwareAsyncFnMut::call_mut(&mut c));
        assert_eq!(r, 10);

        // ThreadAwareAsyncFnOnce::call_once (Box<Self>)
        let c = async_closure(10_i32, |x| Box::pin(async move { *x }));
        let boxed: Box<dyn ThreadAwareAsyncFnOnce<i32>> = Box::new(c);
        let r = futures::executor::block_on(boxed.call_once());
        assert_eq!(r, 10);
    }

    #[test]
    fn async_closure_once_debug_and_clone() {
        let c = async_closure_once(String::from("hello"), |x| Box::pin(async move { x }));
        let dbg = format!("{c:?}");
        assert!(dbg.contains("AsyncClosureOnce"), "{dbg}");
        let c2 = c.clone();
        let r = futures::executor::block_on(c2.call_once());
        assert_eq!(r, "hello");
        // Use original after clone to prove clone is not redundant
        let r2 = futures::executor::block_on(c.call_once());
        assert_eq!(r2, "hello");
    }

    #[test]
    fn async_closure_once_trait_call_once() {
        // ThreadAwareAsyncFnOnce::call_once (Box<Self>)
        let c = async_closure_once(99_i32, |x| Box::pin(async move { x }));
        let boxed: Box<dyn ThreadAwareAsyncFnOnce<i32>> = Box::new(c);
        let r = futures::executor::block_on(boxed.call_once());
        assert_eq!(r, 99);
    }

    #[test]
    fn async_closure_mut_debug_and_clone() {
        let c = async_closure_mut(String::from("hello"), |x| {
            let v = x.clone();
            Box::pin(async move { v })
        });
        let dbg = format!("{c:?}");
        assert!(dbg.contains("AsyncClosureMut"), "{dbg}");
        let mut c2 = c.clone();
        let r = futures::executor::block_on(c2.call_mut());
        assert_eq!(r, "hello");
        // Use original after clone to prove clone is not redundant
        drop(c);
    }

    #[test]
    fn async_closure_mut_trait_impls() {
        // ThreadAwareAsyncFnMut::call_mut
        let mut c = async_closure_mut(10_i32, |x| {
            let v = *x;
            Box::pin(async move { v })
        });
        let r = futures::executor::block_on(ThreadAwareAsyncFnMut::call_mut(&mut c));
        assert_eq!(r, 10);

        // ThreadAwareAsyncFnOnce::call_once (Box<Self>)
        let c = async_closure_mut(10_i32, |x| {
            let v = *x;
            Box::pin(async move { v })
        });
        let boxed: Box<dyn ThreadAwareAsyncFnOnce<i32>> = Box::new(c);
        let r = futures::executor::block_on(boxed.call_once());
        assert_eq!(r, 10);
    }
}