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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
use std::collections::VecDeque;
use std::fmt::Debug;
use std::num::NonZero;

use foldhash::{HashMap, HashMapExt, HashSet, HashSetExt};
use itertools::Itertools;
use nonempty::NonEmpty;
use rand::prelude::*;
use rand::rng;

use crate::pal::Platform;
use crate::{
    EfficiencyClass, MemoryRegionId, Processor, ProcessorId, ProcessorSet, SystemHardware,
};

/// Builds a [`ProcessorSet`] based on specified criteria.
///
/// You can obtain an instance by calling [`ProcessorSet::to_builder()`] on an existing [`ProcessorSet`],
/// typically either [`SystemHardware::processors()`] or [`SystemHardware::all_processors()`].
/// # External constraints
///
/// The operating system may define constraints that prohibit the application from using all
/// the available processors (e.g. when the app is containerized and provided limited
/// hardware resources).
///
/// This package treats platform constraints as follows:
///
/// * Hard limits on which processors are allowed are respected - forbidden processors are mostly
///   ignored by this package and cannot be used to spawn threads, though such processors are still
///   accounted for when inspecting hardware information such as "max processor ID".
///   The mechanisms for defining such limits are cgroups on Linux and job objects on Windows.
///   See `examples/obey_job_affinity_limits_windows.rs` for a Windows-specific example.
/// * Soft limits on which processors are allowed are ignored by default - specifying a processor
///   affinity via `taskset` on Linux, `start.exe /affinity 0xff` on Windows or similar mechanisms
///   does not affect the set of processors this package will use by default, though you can opt in to
///   this via [`.where_available_for_current_thread()`][crate::ProcessorSetBuilder::where_available_for_current_thread].
/// * Any operating system enforced processor time quota is taken as the upper bound for the processor
///   count of the processor set returned by [`SystemHardware::processors()`].
/// * Any other processor set can be opt-in quota-limited when building the processor set. For example, by calling `SystemHardware::current().all_processors().to_builder().enforce_resource_quota().take_all()`.
///
/// See `examples/obey_job_resource_quota_limits_windows.rs` for a Windows-specific example of processor
/// time quota enforcement.
///
/// # Avoiding operating system quota penalties
///
/// If a process exceeds the processor time limit, the operating system will delay executing the
/// process further until the "debt is paid off". This is undesirable for most workloads because:
///
/// 1. There will be random latency spikes from when the operating system decides to apply a delay.
/// 1. The delay may not be evenly applied across all threads of the process, leading to unbalanced
///    load between worker threads.
///
/// For predictable behavior that does not suffer from delay side-effects, it is important that the
/// process does not exceed the processor time limit. To keep out of trouble,
/// follow these guidelines:
///
/// * Ensure that all your concurrently executing thread pools are derived from the same processor
///   set, so there is a single set of processors (up to the resource quota) that all work of the
///   process will be executed on. Any new processor sets you create should be subsets of this set,
///   thereby ensuring that all worker threads combined do not exceed the quota.
/// * Ensure that the original processor set is constructed while obeying the resource quota (which is
///   enabled by default).
///
/// If your resource constraints are already applied on process startup, you can use
/// `SystemHardware::current().processors()` as the master set from which all other
/// processor sets are derived using either `.take()` or `.to_builder()`. This will ensure the
/// processor time quota is obeyed because `processors()` is size-limited to the quota.
///
/// ```rust
/// # use many_cpus::SystemHardware;
/// # use new_zealand::nz;
/// let hw = SystemHardware::current();
///
/// // By taking both senders and receivers from the same original processor set, we
/// // guarantee that all worker threads combined cannot exceed the processor time quota.
/// let mail_senders = hw
///     .processors()
///     .take(nz!(2))
///     .expect("need at least 2 processors for mail workers")
///     .spawn_threads(|_| send_mail());
///
/// let mail_receivers = hw
///     .processors()
///     .take(nz!(2))
///     .expect("need at least 2 processors for mail workers")
///     .spawn_threads(|_| receive_mail());
/// # fn send_mail() {}
/// # fn receive_mail() {}
/// ```
///
/// # Inheriting processor affinity from current thread
///
/// By default, the processor affinity of the current thread is ignored when building a processor
/// set, as this type may be used from a thread with a different processor affinity than the threads
/// one wants to configure.
///
/// However, if you do wish to inherit the processor affinity from the current thread, you may do
/// so by calling [`.where_available_for_current_thread()`] on the builder. This filters out all
/// processors that the current thread is not configured to execute on.
///
/// [`.where_available_for_current_thread()`]: ProcessorSetBuilder::where_available_for_current_thread
/// [`SystemHardware::processors()`]: crate::SystemHardware::processors
/// [`SystemHardware::all_processors()`]: crate::SystemHardware::all_processors
#[derive(Clone, Debug)]
pub struct ProcessorSetBuilder {
    processor_type_selector: ProcessorTypeSelector,
    memory_region_selector: MemoryRegionSelector,

    except_indexes: HashSet<ProcessorId>,

    obey_resource_quota: bool,

    /// When set, only processors with IDs in this set are considered as candidates.
    /// When `None`, all platform processors are considered.
    source_processor_ids: Option<HashSet<ProcessorId>>,

    /// The hardware instance to use for pin status tracking and platform access.
    /// Passed to any processor set we create.
    hardware: SystemHardware,
}

impl ProcessorSetBuilder {
    #[must_use]
    pub(crate) fn with_internals(hardware: SystemHardware) -> Self {
        Self {
            processor_type_selector: ProcessorTypeSelector::Any,
            memory_region_selector: MemoryRegionSelector::Any,
            except_indexes: HashSet::new(),
            obey_resource_quota: false,
            source_processor_ids: None,
            hardware,
        }
    }

    /// Restricts the builder to only consider processors from the given set.
    /// This is used internally when building from an existing `ProcessorSet`.
    #[must_use]
    pub(crate) fn source_processors(mut self, processors: &NonEmpty<Processor>) -> Self {
        let ids: HashSet<ProcessorId> = processors.iter().map(Processor::id).collect();
        self.source_processor_ids = Some(ids);
        self
    }

    /// Requires that all processors in the set be marked as [performance processors][1].
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    /// use new_zealand::nz;
    ///
    /// // Get up to 4 performance processors (or fewer if not available)
    /// let performance_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .performance_processors_only()
    ///     .take(nz!(4));
    ///
    /// if let Some(processors) = performance_processors {
    ///     println!("Found {} performance processors", processors.len());
    /// } else {
    ///     println!("Could not find 4 performance processors");
    /// }
    /// ```
    ///
    /// [1]: EfficiencyClass::Performance
    #[must_use]
    pub fn performance_processors_only(mut self) -> Self {
        self.processor_type_selector = ProcessorTypeSelector::Performance;
        self
    }

    /// Requires that all processors in the set be marked as [efficiency processors][1].
    ///
    /// # Example
    ///
    /// ```
    /// use std::num::NonZero;
    ///
    /// use many_cpus::SystemHardware;
    ///
    /// // Get all available efficiency processors for background tasks
    /// let efficiency_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .efficiency_processors_only()
    ///     .take_all();
    ///
    /// if let Some(processors) = efficiency_processors {
    ///     println!(
    ///         "Using {} efficiency processors for background work",
    ///         processors.len()
    ///     );
    ///
    ///     // Spawn threads on efficiency processors to handle background tasks
    ///     let threads = processors.spawn_threads(|processor| {
    ///         println!(
    ///             "Background worker started on efficiency processor {}",
    ///             processor.id()
    ///         );
    ///         // Background work here...
    ///     });
    /// # for thread in threads { thread.join().unwrap(); }
    /// }
    /// ```
    ///
    /// [1]: EfficiencyClass::Efficiency
    #[must_use]
    pub fn efficiency_processors_only(mut self) -> Self {
        self.processor_type_selector = ProcessorTypeSelector::Efficiency;
        self
    }

    /// Requires that all processors in the set be from different memory regions, selecting a
    /// maximum of 1 processor from each memory region.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    /// use new_zealand::nz;
    ///
    /// // Get one processor from each memory region for distributed processing
    /// let distributed_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .different_memory_regions()
    ///     .take(nz!(4));
    ///
    /// if let Some(processors) = distributed_processors {
    ///     println!(
    ///         "Selected {} processors from different memory regions",
    ///         processors.len()
    ///     );
    ///
    ///     // Each processor will be in a different memory region,
    ///     // ideal for parallel work on separate data sets
    ///     for processor in &processors {
    ///         println!(
    ///             "Processor {} in memory region {}",
    ///             processor.id(),
    ///             processor.memory_region_id()
    ///         );
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn different_memory_regions(mut self) -> Self {
        self.memory_region_selector = MemoryRegionSelector::RequireDifferent;
        self
    }

    /// Requires that all processors in the set be from the same memory region.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    /// use new_zealand::nz;
    ///
    /// // Get processors from the same memory region for data locality
    /// let local_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .same_memory_region()
    ///     .take(nz!(3));
    ///
    /// if let Some(processors) = local_processors {
    ///     println!(
    ///         "Selected {} processors from the same memory region",
    ///         processors.len()
    ///     );
    ///
    ///     // All processors share the same memory region for optimal data sharing
    ///     let memory_region = processors.processors().first().memory_region_id();
    ///     println!("All processors are in memory region {}", memory_region);
    ///
    ///     // Ideal for cooperative processing of shared data
    ///     let threads = processors.spawn_threads(|processor| {
    ///         println!(
    ///             "Worker on processor {} accessing shared memory region {}",
    ///             processor.id(),
    ///             processor.memory_region_id()
    ///         );
    ///         // Process shared data here...
    ///     });
    /// # for thread in threads { thread.join().unwrap(); }
    /// }
    /// ```
    #[must_use]
    pub fn same_memory_region(mut self) -> Self {
        self.memory_region_selector = MemoryRegionSelector::RequireSame;
        self
    }

    /// Declares a preference that all processors in the set be from different memory regions,
    /// though will select multiple processors from the same memory region as needed to satisfy
    /// the requested processor count (while keeping the spread maximal).
    #[must_use]
    pub fn prefer_different_memory_regions(mut self) -> Self {
        self.memory_region_selector = MemoryRegionSelector::PreferDifferent;
        self
    }

    /// Declares a preference that all processors in the set be from the same memory region,
    /// though will select processors from different memory regions as needed to satisfy the
    /// requested processor count (while keeping the spread minimal).
    #[must_use]
    pub fn prefer_same_memory_region(mut self) -> Self {
        self.memory_region_selector = MemoryRegionSelector::PreferSame;
        self
    }

    /// Uses a predicate to identify processors that are valid candidates for building the
    /// processor set, with a return value of `bool` indicating that a processor is a valid
    /// candidate for selection into the set.
    ///
    /// The candidates are passed to this function without necessarily first considering all other
    /// conditions - even if this predicate returns `true`, the processor may end up being filtered
    /// out by other conditions. Conversely, some candidates may already be filtered out before
    /// being passed to this predicate.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::{EfficiencyClass, SystemHardware};
    /// use new_zealand::nz;
    ///
    /// // Select only even-numbered performance processors
    /// let filtered_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .filter(|p| p.efficiency_class() == EfficiencyClass::Performance && p.id() % 2 == 0)
    ///     .take(nz!(2));
    ///
    /// if let Some(processors) = filtered_processors {
    ///     for processor in &processors {
    ///         println!(
    ///             "Selected processor {} (performance, even ID)",
    ///             processor.id()
    ///         );
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn filter(mut self, predicate: impl Fn(&Processor) -> bool) -> Self {
        // We invoke the filters immediately because the API gets really annoying if the
        // predicate has to borrow some stuff because it would need to be 'static and that
        // is cumbersome (since we do not return a generic-lifetimed thing back to the caller).
        for processor in self.candidate_processors() {
            if !predicate(&processor) {
                self.except_indexes.insert(processor.id());
            }
        }

        self
    }

    /// Removes specific processors from the set of candidates.
    ///
    /// # Example
    ///
    /// ```
    /// use std::num::NonZero;
    ///
    /// use many_cpus::SystemHardware;
    ///
    /// // Get the default set and remove the first processor
    /// let all_processors = SystemHardware::current().processors();
    /// let first_processor = all_processors.processors().first().clone();
    ///
    /// let remaining_processors = all_processors
    ///     .to_builder()
    ///     .except([&first_processor])
    ///     .take_all();
    ///
    /// if let Some(processors) = remaining_processors {
    ///     println!(
    ///         "Using {} processors (excluding processor {})",
    ///         processors.len(),
    ///         first_processor.id()
    ///     );
    /// }
    /// ```
    #[must_use]
    pub fn except<'a, I>(mut self, processors: I) -> Self
    where
        I: IntoIterator<Item = &'a Processor>,
    {
        for processor in processors {
            self.except_indexes.insert(processor.id());
        }

        self
    }

    /// Removes processors from the set of candidates if they are not available for use by the
    /// current thread.
    ///
    /// This is a convenient way to identify the set of processors the platform prefers a process
    /// to use when called from a non-customized thread such as the `main()` entrypoint.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// // Get processors available to the current thread (respects OS affinity settings)
    /// let available_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .where_available_for_current_thread()
    ///     .take_all()
    ///     .expect("current thread must be running on at least one processor");
    ///
    /// println!(
    ///     "Current thread can use {} processors",
    ///     available_processors.len()
    /// );
    ///
    /// // Compare with all processors on the system
    /// let all_processors = SystemHardware::current().all_processors();
    ///
    /// if available_processors.len() < all_processors.len() {
    ///     println!("Thread affinity is restricting processor usage");
    ///     println!("  Total system processors: {}", all_processors.len());
    ///     println!("  Available to this thread: {}", available_processors.len());
    /// }
    /// ```
    #[must_use]
    pub fn where_available_for_current_thread(mut self) -> Self {
        let current_thread_processors = self.hardware.platform().current_thread_processors();

        for processor in self.candidate_processors() {
            if !current_thread_processors.contains(&processor.id()) {
                self.except_indexes.insert(processor.id());
            }
        }

        self
    }

    /// Enforces the process resource quota when determining the maximum number of processors
    /// that can be included in the created processor set.
    ///
    /// By default, the builder does not enforce the resource quota. Call this method to limit
    /// the processor set to the quota. See the type-level documentation for more details on
    /// resource quota handling best practices.
    ///
    /// Note that [`SystemHardware::processors()`] already enforces the resource quota, so you
    /// do not need to call this method when deriving from that processor set.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    /// use new_zealand::nz;
    ///
    /// // Get all processors and explicitly enforce resource quota.
    /// let quota_processors = SystemHardware::current()
    ///     .all_processors()
    ///     .to_builder()
    ///     .enforce_resource_quota()
    ///     .take(nz!(4));
    /// ```
    ///
    /// [`SystemHardware::processors()`]: crate::SystemHardware::processors
    #[must_use]
    pub fn enforce_resource_quota(mut self) -> Self {
        self.obey_resource_quota = true;
        self
    }

    /// Creates a processor set with a specific number of processors that match the
    /// configured criteria.
    ///
    /// If multiple candidate sets are a match, returns an arbitrary one of them. For example, if
    /// there are six valid candidate processors then `take(4)` may return any four of them.
    ///
    /// Returns `None` if there were not enough candidate processors to satisfy the request.
    ///
    /// # Resource quota
    ///
    /// By default, the resource quota is not enforced. Call [`enforce_resource_quota()`][1]
    /// to limit results to the quota. See the type-level documentation for more details on
    /// resource quota handling best practices.
    ///
    /// [1]: ProcessorSetBuilder::enforce_resource_quota
    #[must_use]
    pub fn take(self, count: NonZero<usize>) -> Option<ProcessorSet> {
        if let Some(max_count) = self.resource_quota_processor_count_limit()
            && count.get() > max_count
        {
            // We cannot satisfy the request.
            return None;
        }

        let candidates = self.candidates_by_memory_region();

        if candidates.is_empty() {
            // No candidates to choose from - everything was filtered out.
            return None;
        }

        let processors = match self.memory_region_selector {
            MemoryRegionSelector::Any => {
                // We do not care about memory regions, so merge into one big happy family and
                // pick a random `count` processors from it. As long as there is enough!
                let all_processors = candidates
                    .values()
                    .flat_map(|x| x.iter().cloned())
                    .collect::<Vec<_>>();

                if all_processors.len() < count.get() {
                    // Not enough processors to satisfy request.
                    return None;
                }

                all_processors
                    .choose_multiple(&mut rng(), count.get())
                    .cloned()
                    .collect_vec()
            }
            MemoryRegionSelector::PreferSame => {
                // We will start decrementing it to zero.
                let count = count.get();

                // We shuffle the memory regions and sort them by size, so if there are memory
                // regions with different numbers of candidates we will prefer the ones with more,
                // although we will consider all memory regions with at least 'count' candidates
                // as equal in sort order to avoid needlessly preferring giant memory regions.
                let mut remaining_memory_regions = candidates.keys().copied().collect_vec();
                remaining_memory_regions.shuffle(&mut rng());
                remaining_memory_regions.sort_unstable_by_key(|x| {
                    candidates
                        .get(x)
                        .expect("region must exist - we just got it from there")
                        .len()
                        // Clamp the length to `count` to treat all larger regions equally.
                        .min(count)
                });
                // We want to start with the largest memory regions first.
                remaining_memory_regions.reverse();

                let mut remaining_memory_regions = VecDeque::from(remaining_memory_regions);

                let mut processors: Vec<Processor> = Vec::with_capacity(count);

                while processors.len() < count {
                    let memory_region = remaining_memory_regions.pop_front()?;

                    let processors_in_region = candidates.get(&memory_region).expect(
                        "we picked an existing key from an existing HashSet - the values must exist",
                    );

                    // There might not be enough to fill the request, which is fine.
                    let choose_count = count.min(processors_in_region.len());

                    let region_processors = processors_in_region
                        .choose_multiple(&mut rng(), choose_count)
                        .cloned();

                    processors.extend(region_processors);
                }

                processors
            }
            MemoryRegionSelector::RequireSame => {
                // We filter out memory regions that do not have enough candidates and pick a
                // random one from the remaining, then picking a random `count` processors.
                let qualifying_memory_regions = candidates
                    .iter()
                    .filter_map(|(region, processors)| {
                        if processors.len() < count.get() {
                            return None;
                        }

                        Some(region)
                    })
                    .collect_vec();

                let memory_region = qualifying_memory_regions.choose(&mut rng())?;

                let processors = candidates.get(memory_region).expect(
                    "we picked an existing key for an existing HashSet - the values must exist",
                );

                processors
                    .choose_multiple(&mut rng(), count.get())
                    .cloned()
                    .collect_vec()
            }
            MemoryRegionSelector::PreferDifferent => {
                // We iterate through the memory regions and prefer one from each, looping through
                // memory regions that still have processors until we have as many as requested.

                // We will start removing processors are memory regions that are used up.
                let mut candidates = candidates;

                let mut processors = Vec::with_capacity(count.get());

                while processors.len() < count.get() {
                    if candidates.is_empty() {
                        // Not enough candidates remaining to satisfy request.
                        return None;
                    }

                    for remaining_processors in candidates.values_mut() {
                        let (index, processor) =
                            remaining_processors.iter().enumerate().choose(&mut rng())?;

                        let processor = processor.clone();

                        remaining_processors.remove(index);

                        processors.push(processor);

                        if processors.len() == count.get() {
                            break;
                        }
                    }

                    // Remove any memory regions that have been depleted.
                    candidates.retain(|_, remaining_processors| !remaining_processors.is_empty());
                }

                processors
            }
            MemoryRegionSelector::RequireDifferent => {
                // We pick random `count` memory regions and a random processor from each.

                if candidates.len() < count.get() {
                    // Not enough memory regions to satisfy request.
                    return None;
                }

                candidates
                    .iter()
                    .choose_multiple(&mut rng(), count.get())
                    .into_iter()
                    .map(|(_, processors)| {
                        processors.iter().choose(&mut rng()).cloned().expect(
                            "we are picking one item from a non-empty list - item must exist",
                        )
                    })
                    .collect_vec()
            }
        };

        Some(ProcessorSet::new(
            NonEmpty::from_vec(processors)?,
            self.hardware,
        ))
    }

    /// Returns a processor set with all processors that match the configured criteria.
    ///
    /// If multiple alternative non-empty sets are a match, returns an arbitrary one of them.
    /// For example, if specifying only a "same memory region" constraint, it will return all
    /// the processors in an arbitrary memory region with at least one qualifying processor.
    ///
    /// Returns `None` if there were no matching processors to satisfy the request.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    ///
    /// // Try to get all efficiency processors, but exclude the first two
    /// let all_processors = SystemHardware::current().processors();
    /// let first_two: Vec<_> = all_processors.processors().iter().take(2).collect();
    ///
    /// let filtered_processors = SystemHardware::current()
    ///     .processors()
    ///     .to_builder()
    ///     .efficiency_processors_only()
    ///     .except(first_two)
    ///     .take_all();
    ///
    /// match filtered_processors {
    ///     Some(processors) => {
    ///         println!(
    ///             "Found {} efficiency processors (excluding first two)",
    ///             processors.len()
    ///         );
    ///
    ///         // Use remaining efficiency processors for background work
    ///         let threads = processors.spawn_threads(|processor| {
    ///             println!("Background worker on processor {}", processor.id());
    ///             // Background processing here...
    ///         });
    /// # for thread in threads { thread.join().unwrap(); }
    ///     }
    ///     None => {
    ///         // This can happen if all efficiency processors were excluded by the filter
    ///         println!("No efficiency processors remaining after filtering");
    ///     }
    /// }
    /// ```
    ///
    /// # Resource quota
    ///
    /// By default, the resource quota is not enforced. Call [`enforce_resource_quota()`][1]
    /// to limit results to the quota. See the type-level documentation for more details on
    /// resource quota handling best practices.
    ///
    /// [1]: ProcessorSetBuilder::enforce_resource_quota
    #[must_use]
    #[cfg_attr(test, mutants::skip)] // Hangs due to recursive access of OnceLock.
    pub fn take_all(self) -> Option<ProcessorSet> {
        let candidates = self.candidates_by_memory_region();

        if candidates.is_empty() {
            // No candidates to choose from - everything was filtered out.
            return None;
        }

        let processors = match self.memory_region_selector {
            MemoryRegionSelector::Any
            | MemoryRegionSelector::PreferSame
            | MemoryRegionSelector::PreferDifferent => {
                // We return all processors in all memory regions because we have no strong
                // filtering criterion we must follow - all are fine, so we return all.
                candidates
                    .values()
                    .flat_map(|x| x.iter().cloned())
                    .collect()
            }
            MemoryRegionSelector::RequireSame => {
                // We return all processors in a random memory region.
                // The candidate set only contains memory regions with at least 1 processor, so
                // we know that all candidate memory regions are valid and we were not given a
                // count, so even 1 processor is enough to satisfy the "all" criterion.
                let memory_region = candidates
                    .keys()
                    .choose(&mut rng())
                    .expect("we picked a random existing index - element must exist");

                let processors = candidates.get(memory_region).expect(
                    "we picked an existing key for an existing HashSet - the values must exist",
                );

                processors.clone()
            }
            MemoryRegionSelector::RequireDifferent => {
                // We return a random processor from each memory region.
                // The candidate set only contains memory regions with at least 1 processor, so
                // we know that all candidate memory regions have enough to satisfy our needs.
                let processors = candidates.values().map(|processors| {
                    processors
                        .choose(&mut rng())
                        .cloned()
                        .expect("we picked a random item from a non-empty list - item must exist")
                });

                processors.collect()
            }
        };

        let processors = self.reduce_processors_until_under_quota(processors);

        Some(ProcessorSet::new(
            NonEmpty::from_vec(processors)?,
            self.hardware,
        ))
    }

    fn reduce_processors_until_under_quota(&self, processors: Vec<Processor>) -> Vec<Processor> {
        let Some(max_count) = self.resource_quota_processor_count_limit() else {
            return processors;
        };

        let mut processors = processors;

        // If we picked too many, reduce until we are under quota.
        while processors.len() > max_count {
            processors
                .pop()
                .expect("guarded by len-check in loop condition");
        }

        processors
    }

    /// Takes the exact processors specified from the candidate set, returning a new
    /// [`ProcessorSet`] containing only those processors.
    ///
    /// # Panics
    ///
    /// Panics if any of the specified processors are not present in the candidate set.
    ///
    /// # Example
    ///
    /// ```
    /// use many_cpus::SystemHardware;
    /// use nonempty::nonempty;
    ///
    /// let hw = SystemHardware::current();
    /// let candidates = hw.processors();
    ///
    /// // Get the first processor from the set.
    /// let first_processor = candidates.processors().first().clone();
    ///
    /// // Create a new set containing exactly that processor.
    /// let single_processor_set = candidates
    ///     .to_builder()
    ///     .take_exact(nonempty![first_processor]);
    ///
    /// assert_eq!(single_processor_set.len(), 1);
    /// ```
    #[must_use]
    pub fn take_exact(self, processors: NonEmpty<Processor>) -> ProcessorSet {
        let candidates = self.candidates_by_memory_region();
        let candidate_ids: HashSet<_> = candidates
            .values()
            .flat_map(|v| v.iter().map(Processor::id))
            .collect();

        for processor in &processors {
            assert!(
                candidate_ids.contains(&processor.id()),
                "processor {} is not in the candidate set",
                processor.id()
            );
        }

        ProcessorSet::new(processors, self.hardware)
    }

    /// Executes the first stage filters to kick out processors purely based on their individual
    /// characteristics. Whatever pass this filter are valid candidates for selection as long
    /// as the next stage of filtering (the memory region logic) permits it.
    ///
    /// Returns candidates grouped by memory region, with each returned memory region having at
    /// least one candidate processor.
    fn candidates_by_memory_region(&self) -> HashMap<MemoryRegionId, Vec<Processor>> {
        let candidates_iter = self
            .candidate_processors()
            .into_iter()
            .filter_map(move |p| {
                if self.except_indexes.contains(&p.id()) {
                    return None;
                }

                let is_acceptable_type = match self.processor_type_selector {
                    ProcessorTypeSelector::Any => true,
                    ProcessorTypeSelector::Performance => {
                        p.efficiency_class() == EfficiencyClass::Performance
                    }
                    ProcessorTypeSelector::Efficiency => {
                        p.efficiency_class() == EfficiencyClass::Efficiency
                    }
                };

                if !is_acceptable_type {
                    return None;
                }

                Some((p.memory_region_id(), p))
            });

        let mut candidates = HashMap::new();
        for (region, processor) in candidates_iter {
            candidates
                .entry(region)
                .or_insert_with(Vec::new)
                .push(processor);
        }

        candidates
    }

    /// Returns the processors to consider as candidates. If a source processor set was provided
    /// (via `source_processors`), only those processors are returned. Otherwise, all
    /// platform processors are returned.
    fn candidate_processors(&self) -> Vec<Processor> {
        let all = self.all_processors();

        match &self.source_processor_ids {
            Some(source_ids) => all
                .into_iter()
                .filter(|p| source_ids.contains(&p.id()))
                .collect(),
            None => all.into_iter().collect(),
        }
    }

    fn all_processors(&self) -> NonEmpty<Processor> {
        // Cheap conversion, reasonable to do it inline since we do not expect
        // processor set logic to be on the hot path anyway.
        self.hardware
            .platform()
            .get_all_processors()
            .map(Processor::new)
    }

    fn resource_quota_processor_count_limit(&self) -> Option<usize> {
        if self.obey_resource_quota {
            let max_processor_time = self.hardware.platform().max_processor_time();

            // We round down the quota to get a whole number of processors.
            // We specifically round down because our goal with the resource quota is to never
            // exceed it, even by a fraction, as that would cause quality of service degradation.
            #[expect(clippy::cast_sign_loss, reason = "quota cannot be negative")]
            #[expect(
                clippy::cast_possible_truncation,
                reason = "we are correctly rounding to avoid the problem"
            )]
            let max_processor_count = max_processor_time.floor() as usize;

            // We can never restrict to less than 1 processor by quota because that would be
            // nonsense - there is always some available processor time, so at least one
            // processor must be usable. Therefore, we round below 1, and round down above 1.
            Some(max_processor_count.max(1))
        } else {
            None
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
enum MemoryRegionSelector {
    /// The default - memory regions are not considered in processor selection.
    #[default]
    Any,

    /// Processors are all from the same memory region. If there are not enough processors in any
    /// memory region, the request will fail.
    RequireSame,

    /// Processors are all from the different memory regions. If there are not enough memory
    /// regions, the request will fail.
    RequireDifferent,

    /// Processors are ideally all from the same memory region. If there are not enough processors
    /// in a single memory region, more memory regions will be added to the candidate set as needed,
    /// but still keeping it to as few as possible.
    PreferSame,

    /// Processors are ideally all from the different memory regions. If there are not enough memory
    /// regions, multiple processors from the same memory region will be returned, but still keeping
    /// to as many different memory regions as possible to spread the processors out.
    PreferDifferent,
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
enum ProcessorTypeSelector {
    /// The default - all processors are valid candidates.
    #[default]
    Any,

    /// Only performance processors (faster, energy-hungry) are valid candidates.
    ///
    /// Every system is guaranteed to have at least one performance processor.
    /// If all processors are of the same performance class,
    /// they are all considered to be performance processors.
    Performance,

    /// Only efficiency processors (slower, energy-efficient) are valid candidates.
    ///
    /// There is no guarantee that any efficiency processors are present on the system.
    Efficiency,
}

#[cfg(not(miri))] // Miri cannot call platform APIs.
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests_real {
    use new_zealand::nz;

    use crate::SystemHardware;

    #[test]
    fn spawn_on_any_processor() {
        let set = SystemHardware::current().processors();
        let result = set.spawn_thread(move |_| 1234).join().unwrap();

        assert_eq!(result, 1234);
    }

    #[test]
    fn spawn_on_every_processor() {
        let set = SystemHardware::current().processors();
        let processor_count = set.len();

        let join_handles = set.spawn_threads(move |_| 4567);

        assert_eq!(join_handles.len(), processor_count);

        for handle in join_handles {
            let result = handle.join().unwrap();
            assert_eq!(result, 4567);
        }
    }

    #[test]
    fn filter_by_memory_region() {
        let hw = SystemHardware::current();

        // We know there is at least one memory region, so these must succeed.
        hw.processors()
            .to_builder()
            .same_memory_region()
            .take_all()
            .unwrap();
        hw.processors()
            .to_builder()
            .same_memory_region()
            .take(nz!(1))
            .unwrap();
        hw.processors()
            .to_builder()
            .different_memory_regions()
            .take_all()
            .unwrap();
        hw.processors()
            .to_builder()
            .different_memory_regions()
            .take(nz!(1))
            .unwrap();
    }

    #[test]
    fn filter_by_efficiency_class() {
        let hw = SystemHardware::current();

        // There must be at least one.
        hw.processors()
            .to_builder()
            .performance_processors_only()
            .take_all()
            .unwrap();
        hw.processors()
            .to_builder()
            .performance_processors_only()
            .take(nz!(1))
            .unwrap();

        // There might not be any. We just try resolving it and ignore the result.
        // As long as it does not panic, we are good.
        drop(
            hw.processors()
                .to_builder()
                .efficiency_processors_only()
                .take_all(),
        );
        drop(
            hw.processors()
                .to_builder()
                .efficiency_processors_only()
                .take(nz!(1)),
        );
    }

    #[test]
    fn filter_in_all() {
        let hw = SystemHardware::current();

        // Ensure we use a constant starting set, in case we are running tests under constraints.
        let starting_set = hw.processors();

        // If we filter in all processors, we should get all of them.
        let processors = starting_set
            .to_builder()
            .filter(|_| true)
            .take_all()
            .unwrap();
        let processor_count = starting_set.len();

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

    #[test]
    fn filter_out_all() {
        let hw = SystemHardware::current();

        // If we filter out all processors, there should be nothing left.
        assert!(
            hw.processors()
                .to_builder()
                .filter(|_| false)
                .take_all()
                .is_none()
        );
    }

    #[test]
    fn except_all() {
        let hw = SystemHardware::current();

        // Ensure we use a constant starting set, in case we are running tests under constraints.
        let starting_set = hw.processors();

        // If we exclude all processors, there should be nothing left.
        assert!(
            starting_set
                .to_builder()
                .except(starting_set.processors().iter())
                .take_all()
                .is_none()
        );
    }
}

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

    use new_zealand::nz;
    use nonempty::nonempty;
    use static_assertions::assert_impl_all;

    use super::*;
    use crate::fake::{HardwareBuilder, ProcessorBuilder};

    assert_impl_all!(ProcessorSetBuilder: UnwindSafe, RefUnwindSafe);

    /// Helper to build a `ProcessorBuilder` with the given properties.
    fn proc(id: u32, memory_region: u32, efficiency_class: EfficiencyClass) -> ProcessorBuilder {
        ProcessorBuilder::new()
            .id(id)
            .memory_region(memory_region)
            .efficiency_class(efficiency_class)
    }

    #[test]
    fn smoke_test() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let set = hw.processors().to_builder().take_all().unwrap();
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn efficiency_class_filter_take() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .efficiency_processors_only()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 0);
    }

    #[test]
    fn efficiency_class_filter_take_all() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .efficiency_processors_only()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 0);
    }

    #[test]
    fn take_n_processors() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .processor(proc(2, 0, EfficiencyClass::Efficiency)),
        );

        let set = hw.processors().to_builder().take(nz!(2)).unwrap();
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn take_n_not_enough_processors() {
        // Configure only 2 processors with low quota so the request for 3 fails.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(2.0),
        );

        let set = hw.processors().to_builder().take(nz!(3));
        assert!(set.is_none());
    }

    #[test]
    fn take_n_not_enough_processor_time_quota() {
        // Configure quota of only 1.0 processor time.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(1.0),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take(nz!(2));
        assert!(set.is_none());
    }

    #[test]
    fn take_n_quota_floors_to_limit() {
        // Configure quota of 1.5 processor time. The floor of 1.5 is 1, so requesting 2
        // processors should fail because the quota limit is less than the requested count.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(1.5),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take(nz!(2));
        assert!(set.is_none());
    }

    #[test]
    fn take_n_exactly_at_quota_limit() {
        // Configure quota of exactly 2.0 processor time and request exactly 2 processors.
        // This tests the boundary condition where count == max_count (should succeed).
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(2.0),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take(nz!(2));
        assert!(set.is_some());
        assert_eq!(set.unwrap().len(), 2);
    }

    #[test]
    fn take_n_under_quota_succeeds() {
        // Configure quota of 3.0 processor time and request only 2 processors.
        // This tests that the quota branch passes through when count < max_count.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .processor(proc(2, 0, EfficiencyClass::Efficiency))
                .max_processor_time(3.0),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take(nz!(2));
        assert!(set.is_some());
        assert_eq!(set.unwrap().len(), 2);
    }

    #[test]
    fn take_n_quota_not_enforced_by_default() {
        // Configure quota of only 1.0 processor time. Since quota is not enforced by default,
        // we should still be able to get all processors via all_processors().to_builder().
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(1.0),
        );

        // Verify that hw.processors() respects the quota limit.
        let limited_set = hw.processors();
        assert_eq!(limited_set.len(), 1);

        // Verify that all_processors().to_builder() does NOT enforce quota by default.
        let set = hw.all_processors().to_builder().take(nz!(2));
        assert_eq!(set.unwrap().len(), 2);
    }

    #[test]
    fn take_n_quota_limit_min_1() {
        // Configure quota of only 0.001 processor time, which should round UP to 1.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(0.001),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take(nz!(1));
        assert_eq!(set.unwrap().len(), 1);
    }

    #[test]
    fn take_all_rounds_down_quota() {
        // Configure quota of 1.999 which should round DOWN to 1.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(1.999),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn take_all_min_1_despite_quota() {
        // Configure quota of 0.001 which should round UP to 1 (never zero).
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(0.001),
        );

        let set = hw
            .all_processors()
            .to_builder()
            .enforce_resource_quota()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn take_all_not_enough_processors() {
        // All processors are efficiency class, so performance filter should fail.
        let hw = SystemHardware::fake(HardwareBuilder::new().processor(proc(
            0,
            0,
            EfficiencyClass::Efficiency,
        )));

        let set = hw
            .processors()
            .to_builder()
            .performance_processors_only()
            .take_all();
        assert!(set.is_none());
    }

    #[test]
    fn except_filter_take() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let builder = hw.processors().to_builder();

        let except_set = builder.clone().filter(|p| p.id() == 0).take_all().unwrap();
        assert_eq!(except_set.len(), 1);

        let set = builder.except(except_set.processors()).take_all().unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 1);
    }

    #[test]
    fn except_filter_take_all() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let builder = hw.processors().to_builder();
        let except_set = builder.clone().filter(|p| p.id() == 0).take_all().unwrap();
        assert_eq!(except_set.len(), 1);

        let set = builder.except(except_set.processors()).take_all().unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 1);
    }

    #[test]
    fn custom_filter_take() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .filter(|p| p.id() == 1)
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 1);
    }

    #[test]
    fn custom_filter_take_all() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .filter(|p| p.id() == 1)
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 1);
    }

    #[test]
    fn same_memory_region_filter_take() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .same_memory_region()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn same_memory_region_filter_take_all() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .same_memory_region()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn different_memory_region_filter_take() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Efficiency))
                .processor(proc(2, 1, EfficiencyClass::Performance))
                .processor(proc(3, 1, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .different_memory_regions()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 2);

        assert_ne!(
            set.processors().first().memory_region_id(),
            set.processors().last().memory_region_id()
        );
    }

    #[test]
    fn different_memory_region_filter_take_all() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Efficiency))
                .processor(proc(2, 1, EfficiencyClass::Performance))
                .processor(proc(3, 1, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .different_memory_regions()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 2);

        assert_ne!(
            set.processors().first().memory_region_id(),
            set.processors().last().memory_region_id()
        );
    }

    #[test]
    fn filter_combinations() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency)),
        );

        let builder = hw.processors().to_builder();
        let except_set = builder.clone().filter(|p| p.id() == 0).take_all().unwrap();
        let set = builder
            .efficiency_processors_only()
            .except(except_set.processors())
            .different_memory_regions()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), 2);
    }

    #[test]
    fn same_memory_region_take_two_processors() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency)),
        );

        let set = hw
            .processors()
            .to_builder()
            .same_memory_region()
            .take(nz!(2))
            .unwrap();
        assert_eq!(set.len(), 2);
        assert!(set.processors().iter().any(|p| p.id() == 1));
        assert!(set.processors().iter().any(|p| p.id() == 2));
    }

    #[test]
    fn different_memory_region_and_efficiency_class_filters() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 2, EfficiencyClass::Efficiency))
                .processor(proc(3, 3, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .different_memory_regions()
            .efficiency_processors_only()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 2);
        assert!(set.processors().iter().any(|p| p.id() == 0));
        assert!(set.processors().iter().any(|p| p.id() == 2));
    }

    #[test]
    fn performance_processors_but_all_efficiency() {
        let hw = SystemHardware::fake(HardwareBuilder::new().processor(proc(
            0,
            0,
            EfficiencyClass::Efficiency,
        )));

        let set = hw
            .processors()
            .to_builder()
            .performance_processors_only()
            .take_all();
        assert!(set.is_none(), "No performance processors should be found.");
    }

    #[test]
    fn require_different_single_region() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Efficiency)),
        );

        let set = hw
            .processors()
            .to_builder()
            .different_memory_regions()
            .take(nz!(2));
        assert!(
            set.is_none(),
            "Should fail because there is not enough distinct memory regions."
        );
    }

    #[test]
    fn prefer_different_memory_regions_take_all() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency)),
        );

        let set = hw
            .processors()
            .to_builder()
            .prefer_different_memory_regions()
            .take_all()
            .unwrap();
        assert_eq!(set.len(), 3);
    }

    #[test]
    fn prefer_different_memory_regions_take_n() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .processor(proc(3, 2, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .prefer_different_memory_regions()
            .take(nz!(2))
            .unwrap();
        assert_eq!(set.len(), 2);
        let regions: HashSet<_> = set
            .processors()
            .iter()
            .map(Processor::memory_region_id)
            .collect();
        assert_eq!(regions.len(), 2);
    }

    #[test]
    fn prefer_same_memory_regions_take_n() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .processor(proc(3, 2, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .prefer_same_memory_region()
            .take(nz!(2))
            .unwrap();
        assert_eq!(set.len(), 2);
        let regions: HashSet<_> = set
            .processors()
            .iter()
            .map(Processor::memory_region_id)
            .collect();
        assert_eq!(regions.len(), 1);
    }

    #[test]
    fn prefer_different_memory_regions_take_n_not_enough() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .processor(proc(3, 2, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .prefer_different_memory_regions()
            .take(nz!(4))
            .unwrap();
        assert_eq!(set.len(), 4);
    }

    #[test]
    fn prefer_same_memory_regions_take_n_not_enough() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .processor(proc(3, 2, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .prefer_same_memory_region()
            .take(nz!(3))
            .unwrap();
        assert_eq!(set.len(), 3);
        let regions: HashSet<_> = set
            .processors()
            .iter()
            .map(Processor::memory_region_id)
            .collect();
        assert_eq!(
            2,
            regions.len(),
            "should have picked to minimize memory regions (biggest first)"
        );
    }

    #[test]
    fn prefer_same_memory_regions_take_n_picks_best_fit() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .processor(proc(3, 2, EfficiencyClass::Performance)),
        );

        let set = hw
            .processors()
            .to_builder()
            .prefer_same_memory_region()
            .take(nz!(2))
            .unwrap();
        assert_eq!(set.len(), 2);
        let regions: HashSet<_> = set
            .processors()
            .iter()
            .map(Processor::memory_region_id)
            .collect();
        assert_eq!(
            1,
            regions.len(),
            "should have picked from memory region 1 which can accommodate the preference"
        );
    }

    #[test]
    fn take_any_returns_none_when_not_enough_processors() {
        // This tests the MemoryRegionSelector::Any branch returning None when there
        // are not enough processors in the candidate set to satisfy the request.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .max_processor_time(10.0),
        );

        // Request more processors than exist (3 > 2). Quota is high so the quota check passes,
        // but there are not enough candidates in the Any branch.
        let set = hw.processors().to_builder().take(nz!(3));
        assert!(
            set.is_none(),
            "should return None when not enough processors available"
        );
    }

    #[test]
    fn take_prefer_different_returns_none_when_candidates_exhausted() {
        // This tests the MemoryRegionSelector::PreferDifferent branch returning None
        // when the round-robin through memory regions exhausts all candidates.
        // Configuration: 2 memory regions with 1 processor each. Request 3 processors.
        // The round-robin will pick 1 from each region (total 2), then have no more
        // candidates to pick from, so it returns None.
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .max_processor_time(10.0),
        );

        // Request 3 processors with prefer_different_memory_regions.
        // We only have 2 total, so after 2 rounds the candidates will be exhausted.
        let set = hw
            .processors()
            .to_builder()
            .prefer_different_memory_regions()
            .take(nz!(3));
        assert!(
            set.is_none(),
            "should return None when candidates exhausted in PreferDifferent mode"
        );
    }

    #[test]
    fn take_exact_returns_set_with_specified_processors() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .max_processor_time(10.0),
        );

        let candidates = hw.all_processors();
        let p1 = candidates.processors().first().clone();

        let set = candidates.to_builder().take_exact(nonempty![p1.clone()]);
        assert_eq!(set.len(), 1);
        assert_eq!(set.processors().first().id(), p1.id());
    }

    #[test]
    fn take_exact_with_multiple_processors() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 1, EfficiencyClass::Performance))
                .processor(proc(2, 1, EfficiencyClass::Efficiency))
                .max_processor_time(10.0),
        );

        let candidates = hw.all_processors();
        let p0 = candidates
            .processors()
            .iter()
            .find(|p| p.id() == 0)
            .cloned()
            .unwrap();
        let p2 = candidates
            .processors()
            .iter()
            .find(|p| p.id() == 2)
            .cloned()
            .unwrap();

        let set = candidates.to_builder().take_exact(nonempty![p0, p2]);
        assert_eq!(set.len(), 2);
        assert!(set.processors().iter().any(|p| p.id() == 0));
        assert!(set.processors().iter().any(|p| p.id() == 2));
    }

    #[test]
    #[should_panic]
    fn take_exact_panics_if_processor_not_in_candidates() {
        let hw = SystemHardware::fake(
            HardwareBuilder::new()
                .processor(proc(0, 0, EfficiencyClass::Efficiency))
                .processor(proc(1, 0, EfficiencyClass::Performance))
                .max_processor_time(10.0),
        );

        let candidates = hw.all_processors();

        // Explicitly find the processor with ID 0 (not relying on ordering).
        let p0 = candidates
            .processors()
            .iter()
            .find(|p| p.id() == 0)
            .cloned()
            .unwrap();

        // Filter out processor 0, then try to take_exact with it - this should panic.
        drop(
            candidates
                .to_builder()
                .filter(|p| p.id() != 0)
                .take_exact(nonempty![p0]),
        );
    }
}

/// Fallback PAL integration tests - these test the integration between `ProcessorSetBuilder`
/// and the fallback platform abstraction layer.
#[cfg(all(test, not(miri)))] // Miri cannot call platform APIs.
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests_fallback {
    use std::num::NonZero;

    use new_zealand::nz;

    use crate::SystemHardware;
    use crate::pal::fallback::BUILD_TARGET_PLATFORM;

    #[test]
    fn builder_smoke_test() {
        let hw = SystemHardware::fallback();
        let builder = hw.processors().to_builder();

        let set = builder.take_all().unwrap();

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

    #[test]
    fn take_respects_limit() {
        let hw = SystemHardware::fallback();
        let builder = hw.processors().to_builder();

        let set = builder.take(nz!(1));

        assert!(set.is_some());
        assert_eq!(set.unwrap().len(), 1);
    }

    #[test]
    fn take_all_returns_all() {
        let hw = SystemHardware::fallback();
        let builder = hw.processors().to_builder();

        let set = builder.take_all().unwrap();

        let expected_count = std::thread::available_parallelism()
            .map(NonZero::get)
            .unwrap_or(1);

        assert_eq!(set.len(), expected_count);
    }

    #[test]
    fn performance_only_filter() {
        // All processors on the fallback platform are Performance class.
        let hw = SystemHardware::fallback();
        let builder = hw.processors().to_builder();

        let set = builder.performance_processors_only().take_all().unwrap();

        let expected_count = std::thread::available_parallelism()
            .map(NonZero::get)
            .unwrap_or(1);

        assert_eq!(set.len(), expected_count);
    }

    #[test]
    fn same_memory_region_filter() {
        // All processors on the fallback platform are in memory region 0.
        let hw = SystemHardware::fallback();
        let builder = hw.processors().to_builder();

        let set = builder.same_memory_region().take_all().unwrap();

        let expected_count = std::thread::available_parallelism()
            .map(NonZero::get)
            .unwrap_or(1);

        assert_eq!(set.len(), expected_count);

        for processor in set.processors() {
            assert_eq!(processor.memory_region_id(), 0);
        }
    }

    #[test]
    fn except_filter() {
        let hw = SystemHardware::fallback();
        let builder = hw.processors().to_builder();

        if BUILD_TARGET_PLATFORM.processor_count() > 1 {
            let except_set = builder.clone().filter(|p| p.id() == 0).take_all().unwrap();
            assert_eq!(except_set.len(), 1);

            let set = builder.except(except_set.processors()).take_all().unwrap();

            for processor in set.processors() {
                assert_ne!(processor.id(), 0);
            }
        }
    }

    #[test]
    fn enforce_resource_quota() {
        let hw = SystemHardware::fallback();
        let builder = hw.all_processors().to_builder();

        let set = builder.enforce_resource_quota().take_all().unwrap();

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

    #[test]
    fn where_available_for_current_thread() {
        use std::thread;

        thread::spawn(|| {
            let hw = SystemHardware::fallback();

            // First pin to one processor.
            let one = hw.processors().to_builder().take(nz!(1)).unwrap();

            one.pin_current_thread_to();

            // Now build a new set inheriting the affinity.
            let set = hw
                .processors()
                .to_builder()
                .where_available_for_current_thread()
                .take_all();

            assert!(set.is_some());
            assert_eq!(set.unwrap().len(), 1);
        })
        .join()
        .unwrap();
    }

    #[test]
    fn quota_not_enforced_by_default_on_builder() {
        let hw = SystemHardware::fallback();
        let builder = hw.all_processors().to_builder();

        let set = builder.take_all().unwrap();

        // The fallback platform reports max_processor_time == processor_count.
        // Since quota is NOT enforced by default, we should get all processors.
        let expected_count = std::thread::available_parallelism()
            .map(NonZero::get)
            .unwrap_or(1);

        assert_eq!(set.len(), expected_count);
    }
}