many_cpus 2.4.0

Efficiently schedule work and inspect the hardware environment on many-processor systems
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
//! Public handle to a system hardware implementation, supporting both real and fake configurations.
//!
//! This module defines the `SystemHardware` type that wraps either the real hardware or a fake
//! simulated platform (when the `test-util` feature is enabled). All hardware-aware APIs
//! flow from the `SystemHardware` instance, enabling multiple isolated platforms to coexist in
//! parallel tests without interference.

use std::any::type_name;
#[cfg(any(test, feature = "test-util"))]
use std::borrow::Borrow;
use std::fmt;
use std::sync::{Arc, OnceLock, RwLock};
use std::thread::ThreadId;

use foldhash::HashMap;
use nonempty::NonEmpty;

#[cfg(any(test, feature = "test-util"))]
use crate::fake::FakePlatform;
#[cfg(any(test, feature = "test-util"))]
use crate::fake::HardwareBuilder;
use crate::pal::{AbstractProcessor, Platform as PlatformTrait, PlatformFacade};
use crate::{
    MemoryRegionId, Processor, ProcessorId, ProcessorSet, ProcessorSetBuilder, ResourceQuota,
};

/// The real system hardware singleton, initialized on first access.
static CURRENT_HARDWARE: OnceLock<SystemHardware> = OnceLock::new();

/// Handle to system hardware, providing access to hardware information and tracking.
///
/// A `SystemHardware` can represent either the real hardware (via [`SystemHardware::current()`])
/// or simulated fake hardware for testing (via `SystemHardware::fake()` when `test-util` is
/// enabled).
///
/// # Example
///
/// ```
/// use many_cpus::SystemHardware;
///
/// let hardware = SystemHardware::current();
///
/// // Access hardware information.
/// let max_processors = hardware.max_processor_count();
/// println!("Maximum {max_processors} processors supported");
///
/// // Access thread-specific tracking.
/// let processor_id = hardware.current_processor_id();
/// println!("This thread is currently executing on processor {processor_id}");
///
/// // Build processor sets.
/// let processors = hardware.processors();
/// println!("Available processors: {}", processors.len());
/// ```
#[derive(Clone)]
pub struct SystemHardware {
    inner: Arc<SystemHardwareInner>,
}

/// Internal state of a `SystemHardware` instance.
struct SystemHardwareInner {
    /// The platform abstraction layer implementation.
    platform: PlatformFacade,

    /// Per-thread state tracked for this instance.
    ///
    /// We use `RwLock` because reads are far more common than writes, and we expect minimal
    /// contention since each thread typically only accesses its own entry.
    thread_states: RwLock<HashMap<ThreadId, ThreadState>>,

    /// Processors indexed by processor ID for O(1) lookup.
    ///
    /// Gaps in the processor ID sequence are represented as `None`.
    all_processors_slice: Box<[Option<Processor>]>,

    /// Maximum processor ID reported by the backend.
    max_processor_id: ProcessorId,

    /// Maximum memory region ID reported by the backend.
    max_memory_region_id: MemoryRegionId,

    /// Cached default processor list (respects resource quotas).
    ///
    /// We cache the processor list rather than a full `ProcessorSet` to avoid a reference cycle.
    /// `ProcessorSet` contains a `SystemHardware` which would create a circular reference back
    /// to `SystemHardwareInner` via its `Arc`.
    cached_processors: OnceLock<NonEmpty<Processor>>,

    /// Cached all processors list (ignores resource quotas).
    ///
    /// Same caching strategy as `cached_processors` to avoid reference cycles.
    cached_all_processors: OnceLock<NonEmpty<Processor>>,
}

/// Per-thread state tracked within a hardware instance.
#[derive(Clone, Default)]
struct ThreadState {
    /// The processor ID the thread is pinned to, if pinned to exactly one processor.
    pinned_processor_id: Option<ProcessorId>,

    /// The memory region ID the thread is pinned to, if all pinned processors share a region.
    pinned_memory_region_id: Option<MemoryRegionId>,
}

impl SystemHardware {
    /// Returns a handle to the current real system hardware.
    ///
    /// This singleton represents the actual hardware the process is running on. The instance
    /// is initialized on first access and reused thereafter. All clones are equivalent.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let processor_count = hardware.max_processor_count();
    /// println!("Running on hardware with up to {processor_count} processors");
    /// ```
    #[must_use]
    pub fn current() -> &'static Self {
        CURRENT_HARDWARE.get_or_init(|| Self::from_platform(PlatformFacade::target()))
    }

    /// Creates fake system hardware for testing purposes.
    ///
    /// This method is only available when the `test-util` feature is enabled. Fake hardware
    /// allows testing code under simulated hardware configurations without requiring the
    /// actual hardware.
    ///
    /// Each fake hardware instance maintains its own state, enabling multiple
    /// fake instances to coexist in parallel tests without interference. Clones
    /// are equivalent and represent the same fake hardware.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    /// use many_cpus::fake::HardwareBuilder;
    /// use new_zealand::nz;
    ///
    /// // Create fake hardware with 4 processors in 2 memory regions.
    /// let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(2)));
    ///
    /// // Use the hardware just like the real one.
    /// assert_eq!(hardware.max_processor_count(), 4);
    /// assert_eq!(hardware.max_memory_region_count(), 2);
    /// ```
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn fake(builder: impl Borrow<HardwareBuilder>) -> Self {
        let backend = FakePlatform::from_builder(builder.borrow());
        Self::from_platform(PlatformFacade::from_fake(backend))
    }

    /// Creates a `SystemHardware` instance using the fallback platform.
    ///
    /// The fallback platform is a simple implementation that does not use platform-specific
    /// APIs and is useful for testing cross-platform behavior.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn fallback() -> Self {
        use crate::pal::fallback::BUILD_TARGET_PLATFORM;

        Self::from_platform(PlatformFacade::Fallback(&BUILD_TARGET_PLATFORM))
    }

    fn from_platform(platform: PlatformFacade) -> Self {
        let all_pal_processors = platform.get_all_processors();
        let max_processor_id = platform.max_processor_id();
        let max_memory_region_id = platform.max_memory_region_id();

        let max_processor_count = (max_processor_id as usize)
            .checked_add(1)
            .expect("unrealistic to have more than an usize worth of processors");
        let mut all_processors = vec![None; max_processor_count];

        for processor in all_pal_processors {
            *all_processors
                .get_mut(processor.id() as usize)
                .expect("encountered processor with ID above max_processor_id") =
                Some(Processor::new(processor));
        }

        Self {
            inner: Arc::new(SystemHardwareInner {
                platform,
                thread_states: RwLock::new(HashMap::default()),
                all_processors_slice: all_processors.into_boxed_slice(),
                max_processor_id,
                max_memory_region_id,
                cached_processors: OnceLock::new(),
                cached_all_processors: OnceLock::new(),
            }),
        }
    }

    /// Returns a processor set containing the default set of processors for the current process.
    ///
    /// The default set potentially includes all processors available to the process but respects
    /// the resource quota imposed by the operating system. This is the set of processors you
    /// should typically use for work scheduling to avoid being penalized by the operating system.
    ///
    /// To customize the processor selection, call [`to_builder()`][ProcessorSet::to_builder]
    /// on the returned set.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    ///
    /// // Get the default set of processors.
    /// let processors = hardware.processors();
    /// println!("Found {} processors", processors.len());
    ///
    /// // To customize the selection, use to_builder():
    /// let performance_only = processors
    ///     .to_builder()
    ///     .performance_processors_only()
    ///     .take_all();
    /// ```
    #[must_use]
    pub fn processors(&self) -> ProcessorSet {
        let cached = self.inner.cached_processors.get_or_init(|| {
            ProcessorSetBuilder::with_internals(self.clone())
                .enforce_resource_quota()
                .take_all()
                .expect(
                    "there is always at least one processor available because we are running on it",
                )
                .into_processors()
        });

        ProcessorSet::new(cached.clone(), self.clone())
    }

    /// Returns the set of processors that the current thread is pinned to, or `None` if the
    /// thread is not pinned.
    ///
    /// This function only recognizes pinning done via the `many_cpus` package. If you pin a thread
    /// using other means (e.g. `libc`), this function will not be able to detect it.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    ///
    /// // Check if the current thread is pinned.
    /// if let Some(pinned_processors) = hardware.thread_processors() {
    ///     println!("Thread is pinned to {} processors", pinned_processors.len());
    /// } else {
    ///     println!("Thread is not pinned");
    /// }
    /// ```
    #[must_use]
    #[cfg_attr(test, mutants::skip)] // Multiple branches, tested via ProcessorSet::pin_current_thread_to.
    pub fn thread_processors(&self) -> Option<ProcessorSet> {
        // Check if thread is pinned to a single processor.
        if let Some(processor_id) = self.get_pinned_processor_id() {
            let processor = self.get_processor(processor_id).clone();

            return Some(ProcessorSet::new(
                NonEmpty::singleton(processor),
                self.clone(),
            ));
        }

        // Check if thread is pinned to a memory region (but not a single processor).
        if let Some(memory_region_id) = self.get_pinned_memory_region_id() {
            // Get all processors in that memory region.
            let processors: Vec<Processor> = self
                .inner
                .all_processors_slice
                .iter()
                .filter_map(|p| p.as_ref())
                .filter(|p| p.memory_region_id() == memory_region_id)
                .cloned()
                .collect();

            if let Some(processors) = NonEmpty::from_vec(processors) {
                return Some(ProcessorSet::new(processors, self.clone()));
            }
        }

        // Thread is not pinned via many_cpus.
        None
    }

    /// Returns a processor set containing all processors known to the system.
    ///
    /// Unlike [`processors()`][Self::processors], this method ignores resource quotas and
    /// returns all processors regardless of operating system restrictions. This is useful
    /// for system introspection but typically should not be used for work scheduling.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    ///
    /// // Get all processors, ignoring quotas.
    /// let all = hardware.all_processors();
    /// println!("System has {} processors total", all.len());
    ///
    /// // Compare with the default set (respects quotas).
    /// let default = hardware.processors();
    /// if all.len() > default.len() {
    ///     println!(
    ///         "Resource quota limits usage to {} processors",
    ///         default.len()
    ///     );
    /// }
    /// ```
    #[must_use]
    pub fn all_processors(&self) -> ProcessorSet {
        let cached = self.inner.cached_all_processors.get_or_init(|| {
            ProcessorSetBuilder::with_internals(self.clone())
                .take_all()
                .expect("there is always at least one processor available")
                .into_processors()
        });

        ProcessorSet::new(cached.clone(), self.clone())
    }

    /// Returns the highest possible value for a processor ID.
    ///
    /// Processor IDs are in the range `0..=max_processor_id()`.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let max_id = hardware.max_processor_id();
    /// println!("Processor IDs range from 0 to {max_id}");
    /// ```
    #[must_use]
    #[inline]
    pub fn max_processor_id(&self) -> ProcessorId {
        self.inner.max_processor_id
    }

    /// Returns the highest possible value for a memory region ID.
    ///
    /// Memory region IDs are in the range `0..=max_memory_region_id()`.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let max_id = hardware.max_memory_region_id();
    /// println!("Memory region IDs range from 0 to {max_id}");
    /// ```
    #[must_use]
    #[inline]
    #[cfg_attr(test, mutants::skip)] // Trivial field accessor, tested via max_memory_region_count.
    pub fn max_memory_region_id(&self) -> MemoryRegionId {
        self.inner.max_memory_region_id
    }

    /// Returns the maximum number of processors the system could have.
    ///
    /// This is calculated as `max_processor_id() + 1`. Note that not all processor IDs
    /// in the range may correspond to actual processors.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let count = hardware.max_processor_count();
    /// println!("System can have up to {count} processors");
    /// ```
    #[must_use]
    #[inline]
    pub fn max_processor_count(&self) -> usize {
        (self.inner.max_processor_id as usize)
            .checked_add(1)
            .expect("unrealistic to have more than an usize worth of processors")
    }

    /// Returns the maximum number of memory regions the system could have.
    ///
    /// This is calculated as `max_memory_region_id() + 1`. Note that not all memory region IDs
    /// in the range may correspond to actual memory regions.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let count = hardware.max_memory_region_count();
    /// println!("System can have up to {count} memory regions");
    /// ```
    #[must_use]
    #[inline]
    pub fn max_memory_region_count(&self) -> usize {
        (self.inner.max_memory_region_id as usize)
            .checked_add(1)
            .expect("unrealistic to have more than an usize worth of memory regions")
    }

    /// Obtains a reference to the current processor, for the duration of a callback.
    ///
    /// If all you need is the processor ID or memory region ID, you may see better performance
    /// by querying [`current_processor_id()`][Self::current_processor_id] or
    /// [`current_memory_region_id()`][Self::current_memory_region_id] directly.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// hardware.with_current_processor(|processor| {
    ///     println!(
    ///         "Executing on processor {} (class: {:?})",
    ///         processor.id(),
    ///         processor.efficiency_class()
    ///     );
    /// });
    /// ```
    pub fn with_current_processor<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&Processor) -> R,
    {
        let processor_id = self.current_processor_id();
        let processor = self.get_processor(processor_id);
        f(processor)
    }

    /// The ID of the processor currently executing this thread.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let id = hardware.current_processor_id();
    /// println!("Currently executing on processor {id}");
    /// ```
    #[must_use]
    #[inline]
    pub fn current_processor_id(&self) -> ProcessorId {
        self.get_pinned_processor_id()
            .unwrap_or_else(|| self.inner.platform.current_processor_id())
    }

    /// The memory region ID of the processor currently executing this thread.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let region = hardware.current_memory_region_id();
    /// println!("Currently in memory region {region}");
    /// ```
    #[must_use]
    #[inline]
    #[cfg_attr(test, mutants::skip)] // Composition of tested methods.
    pub fn current_memory_region_id(&self) -> MemoryRegionId {
        self.get_pinned_memory_region_id().unwrap_or_else(|| {
            let processor_id = self.current_processor_id();
            self.get_processor(processor_id).memory_region_id()
        })
    }

    /// Whether the current thread is pinned to a single processor.
    ///
    /// Threads may be pinned to any number of processors, not just one - this only checks for
    /// the scenario where the thread is pinned to one specific processor.
    ///
    /// This function only recognizes pinning done via the `many_cpus` package. If you pin a thread
    /// using other means (e.g. `libc`), this function will not be able to detect it.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    ///
    /// // Threads are typically not pinned unless you pin them yourself.
    /// assert!(!hardware.is_thread_processor_pinned());
    /// ```
    #[must_use]
    #[inline]
    pub fn is_thread_processor_pinned(&self) -> bool {
        self.get_pinned_processor_id().is_some()
    }

    /// Whether the current thread is pinned to one or more processors that are all
    /// in the same memory region.
    ///
    /// This function only recognizes pinning done via the `many_cpus` package. If you pin a thread
    /// using other means (e.g. `libc`), this function will not be able to detect it.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    ///
    /// // Threads are typically not pinned unless you pin them yourself.
    /// assert!(!hardware.is_thread_memory_region_pinned());
    /// ```
    #[must_use]
    #[inline]
    pub fn is_thread_memory_region_pinned(&self) -> bool {
        self.get_pinned_memory_region_id().is_some()
    }

    /// Returns the resource quota imposed on this process by the operating system.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let quota = hardware.resource_quota();
    /// println!("Max processor time: {:.2}", quota.max_processor_time());
    /// ```
    #[must_use]
    #[inline]
    pub fn resource_quota(&self) -> ResourceQuota {
        let max_processor_time = self.inner.platform.max_processor_time();
        ResourceQuota::new(max_processor_time)
    }

    /// Returns the number of currently active processors on the system.
    ///
    /// This includes processors that are not available to the current process and
    /// not part of any processor set. This is rarely what you want and is typically only
    /// relevant when interacting with operating system APIs that specifically work with
    /// machine-level processor counts.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// let hardware = SystemHardware::current();
    /// let count = hardware.active_processor_count();
    /// println!("System has {count} active processors");
    /// ```
    #[must_use]
    #[inline]
    pub fn active_processor_count(&self) -> usize {
        self.inner.platform.active_processor_count()
    }

    /// Updates the pinning status for the current thread.
    ///
    /// This is called internally when a thread is pinned to a processor set.
    ///
    /// # Panics
    ///
    /// Panics if `processor_id` is `Some` but `memory_region_id` is `None`, as this is an
    /// invalid state (pinning to a processor implies pinning to its memory region).
    pub(crate) fn update_pin_status(
        &self,
        processor_id: Option<ProcessorId>,
        memory_region_id: Option<MemoryRegionId>,
    ) {
        assert!(
            !(memory_region_id.is_none() && processor_id.is_some()),
            "if processor is pinned, memory region is obviously also pinned"
        );

        let thread_id = std::thread::current().id();
        let mut states = self
            .inner
            .thread_states
            .write()
            .expect("thread state lock should never be poisoned");

        let state = states.entry(thread_id).or_default();
        state.pinned_processor_id = processor_id;
        state.pinned_memory_region_id = memory_region_id;
    }

    /// Gets the pinned processor ID for the current thread, if any.
    fn get_pinned_processor_id(&self) -> Option<ProcessorId> {
        let thread_id = std::thread::current().id();
        let states = self
            .inner
            .thread_states
            .read()
            .expect("thread state lock should never be poisoned");

        states.get(&thread_id)?.pinned_processor_id
    }

    /// Gets the pinned memory region ID for the current thread, if any.
    fn get_pinned_memory_region_id(&self) -> Option<MemoryRegionId> {
        let thread_id = std::thread::current().id();
        let states = self
            .inner
            .thread_states
            .read()
            .expect("thread state lock should never be poisoned");

        states.get(&thread_id)?.pinned_memory_region_id
    }

    /// Gets a processor by ID, with fallback to any available processor if not found.
    fn get_processor(&self, processor_id: ProcessorId) -> &Processor {
        let processor = self.inner.all_processors_slice.get(processor_id as usize);

        if let Some(Some(processor)) = processor {
            processor
        } else {
            // The current processor is one we do not know. This can happen if hardware changed
            // at runtime. Return an arbitrary processor as a fallback.
            self.inner
                .all_processors_slice
                .iter()
                .find_map(|p| p.as_ref())
                .expect("the system must have at least one processor for code to execute")
        }
    }

    /// Returns a reference to the platform abstraction layer.
    pub(crate) fn platform(&self) -> &PlatformFacade {
        &self.inner.platform
    }
}

// We have no API contract for the Debug output format.
#[cfg_attr(coverage_nightly, coverage(off))]
impl fmt::Debug for SystemHardware {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let processor_count = self
            .inner
            .all_processors_slice
            .iter()
            .filter(|p| p.is_some())
            .count();

        f.debug_struct(type_name::<Self>())
            .field("processor_count", &processor_count)
            .field("max_processor_id", &self.inner.max_processor_id)
            .field("max_memory_region_id", &self.inner.max_memory_region_id)
            .finish()
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::panic::{RefUnwindSafe, UnwindSafe};

    use itertools::Itertools;
    use static_assertions::assert_impl_all;

    use super::*;

    assert_impl_all!(SystemHardware: UnwindSafe, RefUnwindSafe);

    #[test]
    fn current_hardware_is_singleton() {
        let h1 = SystemHardware::current();
        let h2 = SystemHardware::current();

        // Both references should point to the same inner data.
        assert!(Arc::ptr_eq(&h1.inner, &h2.inner));
    }

    #[test]
    fn returns_valid_processor_id() {
        let hardware = SystemHardware::current();

        let id = hardware.current_processor_id();

        // The processor ID should be within the valid range.
        assert!(id <= hardware.max_processor_id());
    }

    #[test]
    fn counts_are_positive_values() {
        let hardware = SystemHardware::current();

        // There must be at least one processor and one memory region.
        assert!(hardware.max_processor_count() >= 1);
        assert!(hardware.max_memory_region_count() >= 1);
    }

    #[test]
    fn pin_status_tracking_per_thread() {
        let hardware = SystemHardware::current();

        // Initially not pinned.
        assert!(!hardware.is_thread_processor_pinned());
        assert!(!hardware.is_thread_memory_region_pinned());

        // Update pin status.
        hardware.update_pin_status(Some(0), Some(0));

        // Now pinned.
        assert!(hardware.is_thread_processor_pinned());
        assert!(hardware.is_thread_memory_region_pinned());

        // Clear pin status.
        hardware.update_pin_status(None, None);

        // No longer pinned.
        assert!(!hardware.is_thread_processor_pinned());
        assert!(!hardware.is_thread_memory_region_pinned());
    }

    #[test]
    fn processors_returns_set() {
        let hardware = SystemHardware::current();
        let processors = hardware.processors();

        assert!(processors.len() >= 1);
    }

    #[test]
    fn pinned_current_processor_id_is_unique() {
        // We spawn a thread on every processor and check that the processor ID is unique.
        let hw = SystemHardware::current();

        let mut processor_ids = hw
            .processors()
            .spawn_threads(|processor| {
                let processor_id = processor.id();

                let current_processor_id = hw.current_processor_id();
                assert_eq!(processor_id, current_processor_id);

                current_processor_id
            })
            .into_iter()
            .map(|x| x.join().unwrap())
            .collect_vec();

        // We expect the processor IDs to be unique.
        processor_ids.sort();

        let unique_id_count = processor_ids.iter().dedup().count();

        assert_eq!(unique_id_count, processor_ids.len());
    }

    #[test]
    fn active_processor_count_is_at_least_processor_set_len() {
        // The system may have processors that are not part of any processor set (e.g. because
        // they are not available for the current process) but cannot have more processors in any
        // processor set than the active processor count.
        let hw = SystemHardware::current();
        let all_processors = hw.all_processors();

        let active_processors = hw.active_processor_count();

        // It is OK if all_processors() returns fewer (there are more constraints than "is active").
        assert!(active_processors >= all_processors.len());
    }

    #[test]
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "unavoidable f64-usize casting but we know the value is positive"
    )]
    fn resource_quota_is_followed_by_default() {
        let hw = SystemHardware::current();
        let max_processor_time = hw.resource_quota().max_processor_time();
        let processors = hw.processors();

        // Must be at least 1, since 0 processors is invalid set size.
        let quota_to_processor_time = (max_processor_time.floor() as usize).max(1);

        assert_eq!(quota_to_processor_time, processors.len());
    }

    #[test]
    #[should_panic]
    fn panic_if_pinned_processor_with_unpinned_memory_region() {
        let hardware = SystemHardware::current();
        hardware.update_pin_status(Some(0), None);
    }
}

#[cfg(all(test, feature = "test-util"))]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests_fake {
    use new_zealand::nz;

    use crate::fake::{HardwareBuilder, ProcessorBuilder};
    use crate::{EfficiencyClass, SystemHardware};

    #[test]
    fn fake_hardware_with_simple_config() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));

        assert_eq!(hardware.max_processor_count(), 4);
        assert_eq!(hardware.max_memory_region_count(), 1);
    }

    #[test]
    fn fake_hardware_with_memory_regions() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(6), nz!(3)));

        assert_eq!(hardware.max_processor_count(), 6);
        assert_eq!(hardware.max_memory_region_count(), 3);
    }

    #[test]
    fn fake_hardware_with_custom_processors() {
        let hardware = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(
                    ProcessorBuilder::new()
                        .id(0)
                        .memory_region(0)
                        .efficiency_class(EfficiencyClass::Performance),
                )
                .processor(
                    ProcessorBuilder::new()
                        .id(1)
                        .memory_region(1)
                        .efficiency_class(EfficiencyClass::Efficiency),
                ),
        );

        assert_eq!(hardware.max_processor_count(), 2);
        assert_eq!(hardware.max_memory_region_count(), 2);
    }

    #[test]
    fn fake_hardware_returns_valid_processor_id() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(8), nz!(1)));

        let id = hardware.current_processor_id();

        // The ID should be within the configured range.
        assert!(id < 8);
    }

    #[test]
    fn fake_hardware_pin_status_tracking() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));

        // Initially not pinned.
        assert!(!hardware.is_thread_processor_pinned());
        assert!(!hardware.is_thread_memory_region_pinned());

        // Update pin status.
        hardware.update_pin_status(Some(0), Some(0));

        // Now pinned.
        assert!(hardware.is_thread_processor_pinned());
        assert!(hardware.is_thread_memory_region_pinned());

        // Clear pin status.
        hardware.update_pin_status(None, None);

        // No longer pinned.
        assert!(!hardware.is_thread_processor_pinned());
        assert!(!hardware.is_thread_memory_region_pinned());
    }

    #[test]
    fn fake_hardware_with_hybrid_processors() {
        // 4 performance + 2 efficiency processors.
        let hardware = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(ProcessorBuilder::new().efficiency_class(EfficiencyClass::Performance))
                .processor(ProcessorBuilder::new().efficiency_class(EfficiencyClass::Performance))
                .processor(ProcessorBuilder::new().efficiency_class(EfficiencyClass::Performance))
                .processor(ProcessorBuilder::new().efficiency_class(EfficiencyClass::Performance))
                .processor(ProcessorBuilder::new().efficiency_class(EfficiencyClass::Efficiency))
                .processor(ProcessorBuilder::new().efficiency_class(EfficiencyClass::Efficiency)),
        );

        assert_eq!(hardware.max_processor_count(), 6);
        assert_eq!(hardware.active_processor_count(), 6);
    }

    #[test]
    fn fake_hardware_with_resource_quota() {
        let hardware = SystemHardware::fake(
            HardwareBuilder::from_counts(nz!(8), nz!(1)).max_processor_time(2.5),
        );

        let quota = hardware.resource_quota();

        // The quota should reflect our configuration.
        assert!((quota.max_processor_time() - 2.5).abs() < f64::EPSILON);
    }

    #[test]
    fn multiple_fake_hardware_are_isolated() {
        // Create two different fake hardware instances.
        let hardware1 = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));
        let hardware2 = SystemHardware::fake(HardwareBuilder::from_counts(nz!(8), nz!(1)));

        // They should have different configurations.
        assert_eq!(hardware1.max_processor_count(), 4);
        assert_eq!(hardware2.max_processor_count(), 8);

        // Pin status on one should not affect the other.
        hardware1.update_pin_status(Some(0), Some(0));

        assert!(hardware1.is_thread_processor_pinned());
        assert!(!hardware2.is_thread_processor_pinned());
    }

    #[test]
    fn fake_hardware_clones_share_state() {
        let hardware1 = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));
        let hardware2 = hardware1.clone();

        // Pin status on one should affect the other since they share state.
        hardware1.update_pin_status(Some(0), Some(0));

        assert!(hardware1.is_thread_processor_pinned());
        assert!(hardware2.is_thread_processor_pinned());
    }

    #[test]
    fn fake_hardware_processors_returns_set() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));
        let processors = hardware.processors();

        assert_eq!(processors.len(), 4);
    }

    #[test]
    fn thread_processors_returns_none_when_not_pinned() {
        // Run in new thread to ensure clean pin state.
        std::thread::spawn(|| {
            let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));

            // Without any pinning, thread_processors() should return None.
            let result = hardware.thread_processors();
            assert!(result.is_none());
        })
        .join()
        .unwrap();
    }

    #[test]
    fn thread_processors_returns_single_processor_when_pinned_to_one() {
        std::thread::spawn(|| {
            let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));

            // Pin to a single processor.
            let single = hardware.processors().take(nz!(1)).unwrap();
            single.pin_current_thread_to();

            // thread_processors() should return exactly that processor.
            let result = hardware.thread_processors().unwrap();
            assert_eq!(result.len(), 1);
            assert_eq!(
                result.processors().first().id(),
                single.processors().first().id()
            );
        })
        .join()
        .unwrap();
    }

    #[test]
    fn thread_processors_returns_all_region_processors_when_pinned_to_same_region() {
        std::thread::spawn(|| {
            // Create 4 processors, all in region 0.
            let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(4), nz!(1)));

            // Pin to 2 processors in the same region.
            let two = hardware.processors().take(nz!(2)).unwrap();
            two.pin_current_thread_to();

            // thread_processors() should return all processors in that memory region.
            let result = hardware.thread_processors().unwrap();

            // With same memory region, we get all processors in that region.
            assert_eq!(result.len(), 4);
        })
        .join()
        .unwrap();
    }

    #[test]
    fn max_processor_id_returns_configured_value() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(8), nz!(4)));

        // With 8 processors, max ID should be 7 (0-indexed).
        assert_eq!(hardware.max_processor_id(), 7);
    }

    #[test]
    fn max_memory_region_id_returns_configured_value() {
        let hardware = SystemHardware::fake(HardwareBuilder::from_counts(nz!(8), nz!(4)));

        // With 4 memory regions, max ID should be 3 (0-indexed).
        assert_eq!(hardware.max_memory_region_id(), 3);
    }

    #[test]
    fn get_processor_falls_back_for_unknown_id() {
        // Create hardware with a gap: only processors 0 and 5 exist.
        let hardware = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(ProcessorBuilder::new().id(0).memory_region(0))
                .processor(ProcessorBuilder::new().id(5).memory_region(0)),
        );

        // Override the current processor ID to return 3, which is a gap.
        hardware
            .platform()
            .as_fake()
            .set_processor_id_override(Some(3));

        // with_current_processor() calls get_processor() internally.
        // It should fall back to the first available processor (ID 0).
        hardware.with_current_processor(|processor| {
            assert!(processor.id() == 0 || processor.id() == 5);
        });

        // Also exercise current_memory_region_id() which uses the same path.
        let region = hardware.current_memory_region_id();
        assert_eq!(region, 0);

        hardware
            .platform()
            .as_fake()
            .set_processor_id_override(None);
    }
}