injectorpp 0.5.1

Injectorpp is a powerful tool designed to facilitate the writing of unit tests without the need to introduce traits solely for testing purposes. It streamlines the testing process by providing a seamless and efficient way to abstract dependencies, ensuring that your code remains clean and maintainable.
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
#[allow(unused_imports)]
use crate::injector_core::common::*;
use crate::injector_core::internal::*;
pub use crate::interface::func_ptr::FuncPtr;
pub use crate::interface::macros::__assert_future_output;
pub use crate::interface::macros::__type_id_of_val;
pub use crate::interface::verifier::CallCountVerifier;

use std::future::Future;
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;

use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::RwLock;
use std::sync::RwLockReadGuard;
use std::sync::RwLockWriteGuard;

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
use crate::injector_core::thread_local_registry::ThreadRegistration;

/// Normalize a type_name signature by removing anonymous lifetime annotations.
/// Newer Rust versions (1.86+) render elided lifetimes as `&'_ T` instead of `&T`,
/// which causes false signature mismatches.
fn normalize_signature(sig: &str) -> String {
    sig.replace("&'_ ", "&")
}

/// A `Mutex` that never stays poisoned: on panic it just recovers the guard.
#[allow(dead_code)]
struct NoPoisonMutex<T> {
    inner: Mutex<T>,
}

#[allow(dead_code)]
impl<T> NoPoisonMutex<T> {
    const fn new(value: T) -> Self {
        Self {
            inner: Mutex::new(value),
        }
    }

    fn lock(&self) -> MutexGuard<'_, T> {
        match self.inner.lock() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        }
    }
}

/// Global mutex used on non-TLS architectures to serialize all patching.
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
static LOCK_FUNCTION: NoPoisonMutex<()> = NoPoisonMutex::new(());

/// RwLock for coordinating thread-local vs global fakes.
/// - `when_called()` (thread-local) acquires a **read** lock — multiple thread-local
///   tests can run in parallel.
/// - `when_called_globally()` acquires a **write** lock — blocks until all thread-local
///   tests finish, and prevents new tests from starting. This is exactly 0.4.0 behavior
///   for the duration of the global fake.
static GLOBAL_FAKE_LOCK: RwLock<()> = RwLock::new(());

/// A high-level type that holds patch guards so that when it goes out of scope,
/// the original function code is automatically restored.
///
/// # Thread Safety
///
/// On x86_64 and aarch64, InjectorPP uses thread-local dispatch by default: each thread
/// can independently fake the same function to different values without interference.
/// Tests using InjectorPP can run in parallel.
///
/// Use `InjectorPP::new_global()` for 0.4.0-style global patching where fakes are visible
/// to all threads (e.g., when faked functions are called from background timer threads).
/// Global mode acquires an exclusive lock — other tests wait until the global injector drops.
///
/// On other architectures, InjectorPP always uses global patching with a global mutex.
pub struct InjectorPP {
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
    registrations: Vec<ThreadRegistration>,
    guards: Vec<PatchGuard>,
    verifiers: Vec<CallCountVerifier>,
    /// Read guard: held by thread-local fakes. Allows parallel TLS tests.
    /// Write guard: held by global fakes. Blocks all other tests.
    _rw_guard: RwGuard,
    /// When true, `when_called()` uses direct code patching (0.4.0-style global).
    /// When false (default), uses thread-local dispatch.
    use_global: bool,
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
    _not_send: PhantomData<*const ()>,
    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
    _lock: MutexGuard<'static, ()>,
}

/// Holds either a read or write guard on GLOBAL_FAKE_LOCK, or none (transient during upgrade).
/// The guard values are never read directly — they exist solely to keep the lock held.
#[allow(dead_code)]
enum RwGuard {
    None,
    Read(RwLockReadGuard<'static, ()>),
    Write(RwLockWriteGuard<'static, ()>),
}

impl InjectorPP {
    /// Creates a new `InjectorPP` instance with **thread-local** dispatch (default).
    ///
    /// On x86_64 and aarch64, each instance registers thread-local replacements, enabling parallel test execution.
    /// Fakes are only visible on the thread that created the injector.
    ///
    /// Use `new_global()` instead if your faked functions will be called from background threads.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::InjectorPP;
    ///
    /// let injector = InjectorPP::new();
    /// ```
    pub fn new() -> Self {
        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
        {
            // Acquire a read lock — allows parallel TLS tests, blocks while a global fake is active.
            let rw_guard = match GLOBAL_FAKE_LOCK.read() {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
            Self {
                registrations: Vec::new(),
                guards: Vec::new(),
                verifiers: Vec::new(),
                _rw_guard: RwGuard::Read(rw_guard),
                use_global: false,
                _not_send: PhantomData,
            }
        }

        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
        {
            let lock = LOCK_FUNCTION.lock();
            let rw_guard = match GLOBAL_FAKE_LOCK.read() {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
            Self {
                guards: Vec::new(),
                verifiers: Vec::new(),
                _rw_guard: RwGuard::Read(rw_guard),
                use_global: false,
                _lock: lock,
            }
        }
    }

    /// Creates a new `InjectorPP` instance with **global** (0.4.0-style) patching.
    ///
    /// All `when_called()` fakes will use direct code patching, visible to **all threads**.
    /// This acquires an exclusive write lock — other tests (both thread-local and global)
    /// will wait until this instance is dropped.
    ///
    /// Use this when the faked functions will be called from background threads,
    /// timers, or thread pools.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::InjectorPP;
    ///
    /// // All fakes created with this injector are visible to all threads
    /// let injector = InjectorPP::new_global();
    /// ```
    pub fn new_global() -> Self {
        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
        {
            let rw_guard = match GLOBAL_FAKE_LOCK.write() {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
            Self {
                registrations: Vec::new(),
                guards: Vec::new(),
                verifiers: Vec::new(),
                _rw_guard: RwGuard::Write(rw_guard),
                use_global: true,
                _not_send: PhantomData,
            }
        }

        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
        {
            let lock = LOCK_FUNCTION.lock();
            let rw_guard = match GLOBAL_FAKE_LOCK.write() {
                Ok(g) => g,
                Err(e) => e.into_inner(),
            };
            Self {
                guards: Vec::new(),
                verifiers: Vec::new(),
                _rw_guard: RwGuard::Write(rw_guard),
                use_global: true,
                _lock: lock,
            }
        }
    }

    /// On x86_64 with thread-local dispatch, this is a no-op guard since
    /// thread isolation is automatic. On other architectures, it holds
    /// the global mutex to prevent other threads from patching.
    pub fn prevent() -> Preventer {
        #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
        {
            let lock = LOCK_FUNCTION.lock();
            Preventer { _lock: lock }
        }

        #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
        {
            Preventer {
                _not_send: PhantomData,
            }
        }
    }

    /// Begins faking a function.
    ///
    /// Accepts a FuncPtr to the function you want to fake. Use the `func!` macro to obtain this pointer.
    ///
    /// # Parameters
    ///
    /// - `func`: A FuncPtr holds the pointer to the target function obtained via `func!` macro.
    ///
    /// # Returns
    ///
    /// A builder (`WhenCalledBuilder`) to further specify the fake behavior.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// fn fake_exists(_path: &Path) -> bool {
    ///     true
    /// }
    ///
    /// let mut injector = InjectorPP::new();
    /// injector
    ///     .when_called(injectorpp::func!(fn (Path::exists)(&Path) -> bool))
    ///     .will_execute_raw(injectorpp::func!(fn (fake_exists)(&Path) -> bool));
    ///
    /// assert!(Path::new("/non/existent/path").exists());
    /// ```
    pub fn when_called(&mut self, func: FuncPtr) -> WhenCalledBuilder<'_> {
        let when = WhenCalled::new(func.func_ptr_internal);
        WhenCalledBuilder {
            lib: self,
            when,
            expected_signature: func.signature,
            expected_type_id: func.type_id,
        }
    }

    /// Begins faking a function.
    ///
    /// Accepts a FuncPtr to the function you want to fake. Use the `func!` macro to obtain this pointer.
    ///
    /// # Parameters
    ///
    /// - `func`: A FuncPtr holds the pointer to the target function obtained via `func!` macro.
    ///
    /// # Returns
    ///
    /// A builder (`WhenCalledBuilder`) to further specify the fake behavior.
    ///
    /// # Safety
    ///
    /// This method is unsafe because it skips type check.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// fn fake_exists(_path: &Path) -> bool {
    ///     true
    /// }
    ///
    /// let mut injector = InjectorPP::new();
    ///
    /// unsafe {
    ///     injector
    ///         .when_called_unchecked(injectorpp::func_unchecked!(Path::exists))
    ///         .will_execute_raw_unchecked(injectorpp::func_unchecked!(fake_exists));
    /// }
    ///
    /// assert!(Path::new("/non/existent/path").exists());
    /// ```
    pub unsafe fn when_called_unchecked(&mut self, func: FuncPtr) -> WhenCalledBuilder<'_> {
        let when = WhenCalled::new(func.func_ptr_internal);
        WhenCalledBuilder {
            lib: self,
            when,
            expected_signature: "",
            expected_type_id: None,
        }
    }

    /// Begins faking an asynchronous function.
    ///
    /// Accepts a pinned mutable reference to the async function future. Use the `async_func!` macro to obtain this reference.
    ///
    /// # Parameters
    ///
    /// - `_`: A pinned mutable reference to the async function future.
    ///
    /// # Returns
    ///
    /// A builder (`WhenCalledBuilderAsync`) to further specify the async fake behavior.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    ///
    /// async fn async_add_one(x: u32) -> u32 {
    ///     x + 1
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut injector = InjectorPP::new();
    ///     injector
    ///         .when_called_async(injectorpp::async_func!(async_add_one(u32::default()), u32))
    ///         .will_return_async(injectorpp::async_return!(123, u32));
    ///
    ///     let result = async_add_one(5).await;
    ///     assert_eq!(result, 123); // The patched value
    /// }
    /// ```
    pub fn when_called_async<F, T>(
        &mut self,
        fake_pair: (Pin<&mut F>, &'static str),
    ) -> WhenCalledBuilderAsync<'_>
    where
        F: Future<Output = T>,
    {
        let poll_fn: fn(Pin<&mut F>, &mut Context<'_>) -> Poll<T> = <F as Future>::poll;
        let when = WhenCalled::new(unsafe {
            FuncPtr::new(poll_fn as *const (), std::any::type_name_of_val(&poll_fn))
        }.func_ptr_internal);

        let signature = fake_pair.1;
        WhenCalledBuilderAsync {
            lib: self,
            when,
            expected_signature: signature,
            expected_type_id: None,
        }
    }

    /// Begins faking an asynchronous function.
    ///
    /// Accepts a pinned mutable reference to the async function future. Use the `async_func!` macro to obtain this reference.
    ///
    /// # Parameters
    ///
    /// - `_`: A pinned mutable reference to the async function future.
    ///
    /// # Returns
    ///
    /// A builder (`WhenCalledBuilderAsync`) to further specify the async fake behavior.
    ///
    /// # Safety
    ///
    /// This method is unsafe because it skips type check.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    ///
    /// async fn async_add_one(x: u32) -> u32 {
    ///     x + 1
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut injector = InjectorPP::new();
    ///
    ///     unsafe {
    ///         injector
    ///             .when_called_async_unchecked(injectorpp::async_func_unchecked!(async_add_one(u32::default())))
    ///             .will_return_async_unchecked(injectorpp::async_return_unchecked!(123, u32));
    ///     }
    ///
    ///     let result = async_add_one(5).await;
    ///     assert_eq!(result, 123); // The patched value
    /// }
    /// ```
    pub unsafe fn when_called_async_unchecked<F, T>(
        &mut self,
        _: Pin<&mut F>,
    ) -> WhenCalledBuilderAsync<'_>
    where
        F: Future<Output = T>,
    {
        let poll_fn: fn(Pin<&mut F>, &mut Context<'_>) -> Poll<T> = <F as Future>::poll;
        let when = WhenCalled::new(unsafe {
            FuncPtr::new(poll_fn as *const (), std::any::type_name_of_val(&poll_fn))
        }.func_ptr_internal);

        WhenCalledBuilderAsync {
            lib: self,
            when,
            expected_signature: "",
            expected_type_id: None,
        }
    }
}

impl Default for InjectorPP {
    fn default() -> Self {
        Self::new()
    }
}

/// A guard that prevents injectorpp affecting the test while alive.
///
/// On x86_64, this is a no-op since thread-local dispatch naturally isolates threads.
/// On other architectures, this holds the global mutex that prevents patching.
pub struct Preventer {
    #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
    _lock: MutexGuard<'static, ()>,
    #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
    _not_send: PhantomData<*const ()>,
}

impl Preventer {
    /// Check if patching is currently prevented by this guard.
    ///
    /// This always returns `true` while the guard exists.
    pub fn is_active(&self) -> bool {
        true
    }
}

/// A builder that lets you chain patching operations.
pub struct WhenCalledBuilder<'a> {
    lib: &'a mut InjectorPP,
    when: WhenCalled,
    expected_signature: &'static str,
    expected_type_id: Option<std::any::TypeId>,
}

impl WhenCalledBuilder<'_> {
    /// Fake the target function to branch to the provided function.
    ///
    /// Allows full customization of the faked function behavior by providing your own function or closure.
    ///
    /// # Parameters
    ///
    /// - `target`: A FuncPtr holds the pointer to the replacement function or closure. Using injectorpp::func! or injectorpp::closure! macros is recommended to obtain this pointer.
    ///
    /// # Example
    ///
    /// Using closure:
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// let fake_closure = |_: &Path| -> bool {
    ///    true
    /// };
    ///
    /// let mut injector = InjectorPP::new();
    /// injector
    ///     .when_called(injectorpp::func!(fn (Path::exists)(&Path) -> bool))
    ///     .will_execute_raw(injectorpp::closure!(fake_closure, fn(&Path) -> bool));
    ///
    /// assert!(Path::new("/nonexistent").exists());
    /// ```
    ///
    /// Using custom function:
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// fn fake_exists(_path: &Path) -> bool {
    ///     true
    /// }
    ///
    /// let mut injector = InjectorPP::new();
    /// injector
    ///     .when_called(injectorpp::func!(fn (Path::exists)(&Path) -> bool))
    ///     .will_execute_raw(injectorpp::func!(fn (fake_exists)(&Path) -> bool));
    ///
    /// assert!(Path::new("/nonexistent").exists());
    /// ```
    pub fn will_execute_raw(self, target: FuncPtr) {
        match (self.expected_type_id, target.type_id) {
            (Some(expected), Some(actual)) if expected != actual => {
                panic!(
                    "Signature mismatch: expected {:?} but got {:?}",
                    self.expected_signature, target.signature
                );
            }
            (None, _) | (_, None) => {
                if normalize_signature(target.signature)
                    != normalize_signature(self.expected_signature)
                {
                    panic!(
                        "Signature mismatch: expected {:?} but got {:?}",
                        self.expected_signature, target.signature
                    );
                }
            }
            _ => {}
        }

        if self.lib.use_global {
            let guard = self.when.will_execute_guard(target.func_ptr_internal);
            self.lib.guards.push(guard);
        } else {
            #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
            {
                let reg = self.when.will_execute_thread_local(target.func_ptr_internal);
                self.lib.registrations.push(reg);
            }

            #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
            {
                let guard = self.when.will_execute_guard(target.func_ptr_internal);
                self.lib.guards.push(guard);
            }
        }
    }

    /// Fake the target function to branch to the provided function.
    ///
    /// Allows full customization of the faked function behavior by providing your own function or closure.
    ///
    /// # Parameters
    ///
    /// - `target`: A FuncPtr holds the pointer to the replacement function or closure. Using injectorpp::func_unchecked! or injectorpp::closure! macros is recommended to obtain this pointer.
    ///
    /// # Safety
    ///
    /// This method is unsafe because it skips type check.
    ///
    /// # Example
    ///
    /// Using closure:
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// let fake_closure = |_: &Path| -> bool {
    ///    true
    /// };
    ///
    /// let mut injector = InjectorPP::new();
    ///
    /// unsafe {
    ///     injector
    ///         .when_called(injectorpp::func_unchecked!(Path::exists))
    ///         .will_execute_raw_unchecked(injectorpp::closure!(fake_closure, fn(&Path) -> bool));
    /// }
    ///
    /// assert!(Path::new("/nonexistent").exists());
    /// ```
    ///
    /// Using custom function:
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// fn fake_exists(_path: &Path) -> bool {
    ///     true
    /// }
    ///
    /// let mut injector = InjectorPP::new();
    ///
    /// unsafe {
    ///     injector
    ///         .when_called(injectorpp::func_unchecked!(Path::exists))
    ///         .will_execute_raw_unchecked(injectorpp::func_unchecked!(fake_exists));
    /// }
    ///
    /// assert!(Path::new("/nonexistent").exists());
    /// ```
    pub unsafe fn will_execute_raw_unchecked(self, target: FuncPtr) {
        if self.lib.use_global {
            let guard = self.when.will_execute_guard(target.func_ptr_internal);
            self.lib.guards.push(guard);
        } else {
            #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
            {
                let reg = self.when.will_execute_thread_local(target.func_ptr_internal);
                self.lib.registrations.push(reg);
            }

            #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
            {
                let guard = self.when.will_execute_guard(target.func_ptr_internal);
                self.lib.guards.push(guard);
            }
        }
    }

    /// Fake the target function using a fake function generated by the `fake!` macro.
    ///
    /// Suitable for complex scenarios where you specify conditions, assignments, return values, and expected call counts.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    ///
    /// fn original_func(a: &mut i32) -> bool {
    ///     *a = 1;
    ///     false
    /// }
    ///
    /// let mut injector = InjectorPP::new();
    /// injector
    ///     .when_called(injectorpp::func!(fn (original_func)(&mut i32) -> bool))
    ///     .will_execute(injectorpp::fake!(
    ///         func_type: fn(a: &mut i32) -> bool,
    ///         assign: { *a = 6 },
    ///         returns: true,
    ///         times: 1
    ///     ));
    ///
    /// let mut value = 0;
    /// let result = original_func(&mut value);
    ///
    /// assert_eq!(value, 6);
    /// assert_eq!(result, true);
    /// ```
    /// Below are supported options:
    ///
    /// `func_type``: // Required. The signature of the function to fake.
    /// `when``: // Optional. A condition check for the parameters of the function to fake.
    /// `assign``: // Optional. Use to set values to reference variables of the function to fake.
    /// `returns``: // Required for the function has return. Specify what the return value should be.
    /// `times``: // Optional. How many times the function should be called. If the value is not satisfied at the end of the test, the test will fail.
    pub fn will_execute(self, fake_pair: (FuncPtr, CallCountVerifier)) {
        let (fake_func, verifier) = fake_pair;
        self.lib.verifiers.push(verifier);
        self.will_execute_raw(fake_func);
    }

    /// Fake the target function to always return a fixed boolean value.
    ///
    /// This method is convenient for functions that return boolean values.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    /// use std::path::Path;
    ///
    /// let mut injector = InjectorPP::new();
    /// injector
    ///     .when_called(injectorpp::func!(fn (Path::exists)(&Path) -> bool))
    ///     .will_return_boolean(true);
    ///
    /// assert!(Path::new("/nonexistent").exists());
    /// ```
    pub fn will_return_boolean(self, value: bool) {
        // Ensure the target function returns a bool
        if !self.expected_signature.trim().ends_with("-> bool") {
            panic!(
                "Signature mismatch: will_return_boolean requires a function returning bool but got {}",
                self.expected_signature
            );
        }

        if self.lib.use_global {
            let guard = self.when.will_return_boolean_guard(value);
            self.lib.guards.push(guard);
        } else {
            #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
            {
                let reg = self.when.will_return_boolean_thread_local(value);
                self.lib.registrations.push(reg);
            }

            #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
            {
                let guard = self.when.will_return_boolean_guard(value);
                self.lib.guards.push(guard);
            }
        }
    }
}

pub struct WhenCalledBuilderAsync<'a> {
    lib: &'a mut InjectorPP,
    when: WhenCalled,
    expected_signature: &'static str,
    expected_type_id: Option<std::any::TypeId>,
}

impl WhenCalledBuilderAsync<'_> {
    /// Fake the target async function to return a specified async value.
    ///
    /// This method allows you to fake async functions by specifying the return value directly.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    ///
    /// async fn async_func_bool(x: bool) -> bool {
    ///     x
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut injector = InjectorPP::new();
    ///     injector
    ///         .when_called_async(injectorpp::async_func!(async_func_bool(true), bool))
    ///         .will_return_async(injectorpp::async_return!(false, bool));
    ///
    ///     let result = async_func_bool(true).await;
    ///     assert_eq!(result, false);
    /// }
    /// ```
    pub fn will_return_async(self, target: FuncPtr) {
        match (self.expected_type_id, target.type_id) {
            (Some(expected), Some(actual)) if expected != actual => {
                panic!(
                    "Signature mismatch: expected {:?} but got {:?}",
                    self.expected_signature, target.signature
                );
            }
            (None, _) | (_, None) => {
                if normalize_signature(target.signature)
                    != normalize_signature(self.expected_signature)
                {
                    panic!(
                        "Signature mismatch: expected {:?} but got {:?}",
                        self.expected_signature, target.signature
                    );
                }
            }
            _ => {}
        }

        if self.lib.use_global {
            let guard = self.when.will_execute_guard(target.func_ptr_internal);
            self.lib.guards.push(guard);
        } else {
            #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
            {
                let reg = self.when.will_execute_thread_local(target.func_ptr_internal);
                self.lib.registrations.push(reg);
            }

            #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
            {
                let guard = self.when.will_execute_guard(target.func_ptr_internal);
                self.lib.guards.push(guard);
            }
        }
    }

    /// Fake the target async function to return a specified async value.
    ///
    /// This method allows you to fake async functions by specifying the return value directly.
    ///
    /// # Safety
    ///
    /// This method is unsafe because it skips type check.
    ///
    /// # Example
    ///
    /// ```rust
    /// use injectorpp::interface::injector::*;
    ///
    /// async fn async_func_bool(x: bool) -> bool {
    ///     x
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let mut injector = InjectorPP::new();
    ///     
    ///     unsafe {
    ///         injector
    ///             .when_called_async_unchecked(injectorpp::async_func_unchecked!(async_func_bool(true)))
    ///             .will_return_async_unchecked(injectorpp::async_return_unchecked!(false, bool));
    ///     }
    ///
    ///     let result = async_func_bool(true).await;
    ///     assert_eq!(result, false);
    /// }
    /// ```
    pub unsafe fn will_return_async_unchecked(self, target: FuncPtr) {
        if self.lib.use_global {
            let guard = self.when.will_execute_guard(target.func_ptr_internal);
            self.lib.guards.push(guard);
        } else {
            #[cfg(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm"))]
            {
                let reg = self.when.will_execute_thread_local(target.func_ptr_internal);
                self.lib.registrations.push(reg);
            }

            #[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64", target_arch = "arm")))]
            {
                let guard = self.when.will_execute_guard(target.func_ptr_internal);
                self.lib.guards.push(guard);
            }
        }
    }
}