gdt-cpus 0.2606.0

Game Developer's Toolkit for CPU Management
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
//! CPU affinity mask for specifying sets of logical processors.
//!
//! This module provides the [`AffinityMask`] type, which represents a set of
//! logical processor IDs that a thread may run on. Unlike pinning to a single
//! core, affinity masks allow threads to migrate between a specified set of
//! cores, reducing scheduling latency while still constraining execution.

/// Number of `u64` words in the fixed bitset. 16 words = 1024 logical
/// processors, matching the Linux static `cpu_set_t` (`CPU_SETSIZE`).
const WORDS: usize = 16;

/// A cross-platform CPU affinity mask representing a set of logical processors.
///
/// An `AffinityMask` specifies which logical processors (CPU threads) a thread
/// is allowed to execute on. This is useful for:
///
/// - Restricting latency-sensitive threads to performance cores (P-cores)
/// - Restricting background threads to efficiency cores (E-cores)
/// - Allowing thread migration within a subset of cores to reduce scheduling latency
///
/// # Example
///
/// ```
/// use gdt_cpus::AffinityMask;
///
/// // Create a mask for cores 0, 1, and 2
/// let mask = AffinityMask::from_cores(&[0, 1, 2]);
/// assert_eq!(mask.count(), 3);
/// assert!(mask.contains(0));
/// assert!(mask.contains(1));
/// assert!(mask.contains(2));
/// assert!(!mask.contains(3));
/// ```
///
/// # Capacity
///
/// A mask holds up to [`AffinityMask::MAX_LP_COUNT`] (1024) logical processors -
/// the same ceiling as the Linux static `cpu_set_t`, above which the OS affinity
/// APIs require dynamic allocation this crate does not perform. Ids at or above
/// that bound are out of range and are ignored by [`add`](Self::add) /
/// [`remove`](Self::remove) / [`contains`](Self::contains), so the mask can never
/// be forced to allocate or hold an out-of-range bit. The backing store is a fixed
/// `[u64; 16]`, so the type is `Copy` and its `PartialEq`/`Eq`/`Hash` are canonical
/// (two masks compare equal iff they hold the same set, with no representation
/// ambiguity).
///
/// # Platform Behavior
///
/// When used with [`set_thread_affinity`](crate::set_thread_affinity):
///
/// - **Linux/Windows**: The mask is applied directly to constrain thread execution
/// - **macOS**: Returns `Error::Unsupported`; use QoS classes instead
#[must_use = "a mask is built to be applied or inspected; discarding it does nothing"]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AffinityMask {
    /// Fixed bitset: `WORDS` u64 words covering cores 0..1024.
    /// `bits[0]` = cores 0-63, `bits[1]` = 64-127, ..., `bits[15]` = 960-1023.
    bits: [u64; WORDS],
}

impl AffinityMask {
    /// Maximum number of logical processors a mask can represent (1024).
    ///
    /// Matches the Linux static `cpu_set_t` (`CPU_SETSIZE`); the OS affinity APIs
    /// cap here too (beyond it they need dynamic allocation this crate does not do).
    /// Ids at or above this are out of range and ignored by the mutators.
    ///
    /// NOTE(windows): an `os_id` can exceed this only on a >1024-LP machine
    /// (>= 16 processor groups), which is a multi-socket server, not a target.
    pub const MAX_LP_COUNT: usize = WORDS * 64;

    /// Creates an empty affinity mask with no cores set.
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::empty();
    /// assert!(mask.is_empty());
    /// assert_eq!(mask.count(), 0);
    /// ```
    pub fn empty() -> Self {
        Self::default()
    }

    /// Creates an affinity mask with a single core set.
    ///
    /// # Arguments
    ///
    /// * `logical_core_id` - The logical processor ID to include in the mask
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::single(5);
    /// assert_eq!(mask.count(), 1);
    /// assert!(mask.contains(5));
    /// ```
    pub fn single(logical_core_id: usize) -> Self {
        let mut mask = Self::empty();

        mask.add(logical_core_id);

        mask
    }

    /// Creates an affinity mask from a slice of core IDs.
    ///
    /// # Arguments
    ///
    /// * `core_ids` - Slice of logical processor IDs to include
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::from_cores(&[0, 2, 4, 6]);
    /// assert_eq!(mask.count(), 4);
    /// assert!(mask.contains(0));
    /// assert!(!mask.contains(1));
    /// assert!(mask.contains(2));
    /// ```
    pub fn from_cores(core_ids: &[usize]) -> Self {
        let mut mask = Self::empty();

        for &id in core_ids {
            mask.add(id);
        }

        mask
    }

    /// Adds a logical core to the mask.
    ///
    /// If the core is already in the mask, this is a no-op. Ids at or above
    /// [`MAX_LP_COUNT`](Self::MAX_LP_COUNT) are out of range and are ignored.
    ///
    /// # Arguments
    ///
    /// * `logical_core_id` - The logical processor ID to add
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mut mask = AffinityMask::empty();
    /// mask.add(0);
    /// mask.add(1);
    /// assert_eq!(mask.count(), 2);
    /// ```
    pub fn add(&mut self, logical_core_id: usize) {
        if logical_core_id >= Self::MAX_LP_COUNT {
            return;
        }

        let word_idx = logical_core_id / 64;
        let bit_idx = logical_core_id % 64;

        self.bits[word_idx] |= 1u64 << bit_idx;
    }

    /// Removes a logical core from the mask.
    ///
    /// If the core is not in the mask (or is out of range), this is a no-op.
    ///
    /// # Arguments
    ///
    /// * `logical_core_id` - The logical processor ID to remove
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mut mask = AffinityMask::from_cores(&[0, 1, 2]);
    /// mask.remove(1);
    /// assert_eq!(mask.count(), 2);
    /// assert!(!mask.contains(1));
    /// ```
    pub fn remove(&mut self, logical_core_id: usize) {
        if logical_core_id >= Self::MAX_LP_COUNT {
            return;
        }

        let word_idx = logical_core_id / 64;
        let bit_idx = logical_core_id % 64;

        self.bits[word_idx] &= !(1u64 << bit_idx);
    }

    /// Checks if a logical core is in the mask.
    ///
    /// # Arguments
    ///
    /// * `logical_core_id` - The logical processor ID to check
    ///
    /// # Returns
    ///
    /// `true` if the core is in the mask, `false` otherwise (including any id at
    /// or above [`MAX_LP_COUNT`](Self::MAX_LP_COUNT)).
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::from_cores(&[0, 2, 4]);
    /// assert!(mask.contains(0));
    /// assert!(!mask.contains(1));
    /// assert!(mask.contains(2));
    /// ```
    #[must_use]
    pub fn contains(&self, logical_core_id: usize) -> bool {
        if logical_core_id >= Self::MAX_LP_COUNT {
            return false;
        }

        let word_idx = logical_core_id / 64;
        let bit_idx = logical_core_id % 64;

        (self.bits[word_idx] & (1u64 << bit_idx)) != 0
    }

    /// Returns the number of cores in the mask.
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::from_cores(&[0, 1, 2, 3]);
    /// assert_eq!(mask.count(), 4);
    /// ```
    #[must_use]
    pub fn count(&self) -> usize {
        self.bits.iter().map(|w| w.count_ones() as usize).sum()
    }

    /// Returns `true` if the mask is empty (no cores set).
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let empty = AffinityMask::empty();
    /// assert!(empty.is_empty());
    ///
    /// let non_empty = AffinityMask::single(0);
    /// assert!(!non_empty.is_empty());
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.bits.iter().all(|&w| w == 0)
    }

    /// Returns an iterator over the core IDs in the mask.
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::from_cores(&[1, 3, 5]);
    /// let cores: Vec<usize> = mask.iter().collect();
    /// assert_eq!(cores, vec![1, 3, 5]);
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
        self.bits.iter().enumerate().flat_map(|(word_idx, &word)| {
            (0..64).filter_map(move |bit_idx| {
                if (word & (1u64 << bit_idx)) != 0 {
                    Some(word_idx * 64 + bit_idx)
                } else {
                    None
                }
            })
        })
    }

    /// Returns the union of this mask with another.
    ///
    /// The resulting mask contains all cores that are in either mask.
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let a = AffinityMask::from_cores(&[0, 1]);
    /// let b = AffinityMask::from_cores(&[1, 2]);
    /// let union = a.union(&b);
    /// assert_eq!(union.count(), 3);
    /// assert!(union.contains(0));
    /// assert!(union.contains(1));
    /// assert!(union.contains(2));
    /// ```
    pub fn union(&self, other: &AffinityMask) -> AffinityMask {
        let mut bits = [0u64; WORDS];

        for (i, slot) in bits.iter_mut().enumerate() {
            *slot = self.bits[i] | other.bits[i];
        }

        AffinityMask { bits }
    }

    /// Returns the intersection of this mask with another.
    ///
    /// The resulting mask contains only cores that are in both masks.
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let a = AffinityMask::from_cores(&[0, 1, 2]);
    /// let b = AffinityMask::from_cores(&[1, 2, 3]);
    /// let intersection = a.intersection(&b);
    /// assert_eq!(intersection.count(), 2);
    /// assert!(intersection.contains(1));
    /// assert!(intersection.contains(2));
    /// ```
    pub fn intersection(&self, other: &AffinityMask) -> AffinityMask {
        let mut bits = [0u64; WORDS];

        for (i, slot) in bits.iter_mut().enumerate() {
            *slot = self.bits[i] & other.bits[i];
        }

        AffinityMask { bits }
    }

    /// Returns the first 64 cores as a raw `u64` bitmask.
    ///
    /// This is useful for platform APIs that only support 64 cores.
    /// Cores beyond index 63 are not included.
    ///
    /// # Example
    ///
    /// ```
    /// use gdt_cpus::AffinityMask;
    ///
    /// let mask = AffinityMask::from_cores(&[0, 1, 63]);
    /// let raw = mask.as_raw_u64();
    /// assert_eq!(raw, 0x8000_0000_0000_0003);
    /// ```
    pub fn as_raw_u64(&self) -> u64 {
        self.bits[0]
    }

    /// Returns the raw bits as a slice.
    ///
    /// Each element represents 64 cores: `bits[0]` = cores 0-63,
    /// `bits[1]` = cores 64-127, etc. The slice is always
    /// [`MAX_LP_COUNT`](Self::MAX_LP_COUNT)`/ 64` words long.
    pub fn as_raw_bits(&self) -> &[u64] {
        &self.bits
    }
}

impl std::fmt::Debug for AffinityMask {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cores: Vec<usize> = self.iter().collect();

        f.debug_struct("AffinityMask")
            .field("cores", &cores)
            .field("count", &cores.len())
            .finish()
    }
}

impl std::fmt::Display for AffinityMask {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let cores: Vec<usize> = self.iter().collect();

        if cores.is_empty() {
            write!(f, "AffinityMask(empty)")
        } else {
            write!(f, "AffinityMask({:?})", cores)
        }
    }
}

impl FromIterator<usize> for AffinityMask {
    fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
        let mut mask = AffinityMask::empty();

        for id in iter {
            mask.add(id);
        }

        mask
    }
}

impl IntoIterator for &AffinityMask {
    type Item = usize;
    type IntoIter = std::vec::IntoIter<usize>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter().collect::<Vec<_>>().into_iter()
    }
}

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

    #[test]
    fn test_empty_mask() {
        let mask = AffinityMask::empty();
        assert!(mask.is_empty());
        assert_eq!(mask.count(), 0);
        assert!(!mask.contains(0));
    }

    #[test]
    fn test_single_core() {
        let mask = AffinityMask::single(5);
        assert!(!mask.is_empty());
        assert_eq!(mask.count(), 1);
        assert!(mask.contains(5));
        assert!(!mask.contains(4));
    }

    #[test]
    fn test_from_cores() {
        let mask = AffinityMask::from_cores(&[0, 2, 4, 6]);
        assert_eq!(mask.count(), 4);
        assert!(mask.contains(0));
        assert!(!mask.contains(1));
        assert!(mask.contains(2));
    }

    #[test]
    fn test_add_remove() {
        let mut mask = AffinityMask::empty();
        mask.add(0);
        mask.add(1);
        assert_eq!(mask.count(), 2);

        mask.remove(0);
        assert_eq!(mask.count(), 1);
        assert!(!mask.contains(0));
        assert!(mask.contains(1));
    }

    #[test]
    fn test_high_core_ids() {
        let mut mask = AffinityMask::empty();
        mask.add(0);
        mask.add(64);
        mask.add(128);

        assert_eq!(mask.count(), 3);
        assert!(mask.contains(0));
        assert!(mask.contains(64));
        assert!(mask.contains(128));
        assert!(!mask.contains(63));
        assert!(!mask.contains(65));
    }

    #[test]
    fn test_iter() {
        let mask = AffinityMask::from_cores(&[1, 3, 5, 64, 65]);
        let cores: Vec<usize> = mask.iter().collect();
        assert_eq!(cores, vec![1, 3, 5, 64, 65]);
    }

    #[test]
    fn test_as_raw_u64() {
        let mask = AffinityMask::from_cores(&[0, 1, 63]);
        assert_eq!(mask.as_raw_u64(), 0x8000_0000_0000_0003);
    }

    #[test]
    fn test_from_iterator() {
        let mask: AffinityMask = vec![0, 2, 4].into_iter().collect();
        assert_eq!(mask.count(), 3);
        assert!(mask.contains(0));
        assert!(mask.contains(2));
        assert!(mask.contains(4));
    }

    // A fixed backing array makes equality canonical: add-then-remove of a
    // high core leaves the exact same representation as a fresh empty mask
    // (the old Vec<u64> kept a trailing zero word and compared unequal).
    #[test]
    fn test_equality_is_canonical() {
        let mut a = AffinityMask::single(64);
        a.remove(64);
        assert_eq!(a, AffinityMask::empty());

        let wide = AffinityMask::from_cores(&[0, 200]);
        let narrow = AffinityMask::from_cores(&[0]);
        assert_eq!(wide.intersection(&narrow), narrow);
        assert_eq!(narrow.union(&AffinityMask::empty()), narrow);
    }

    // The capacity boundary: 1023 is the last valid core; MAX_LP_COUNT and
    // above are out of range and silently ignored (never an allocation/panic).
    #[test]
    fn test_capacity_boundary() {
        let mut mask = AffinityMask::empty();
        mask.add(AffinityMask::MAX_LP_COUNT - 1); // 1023
        assert!(mask.contains(AffinityMask::MAX_LP_COUNT - 1));
        assert_eq!(mask.count(), 1);

        mask.add(AffinityMask::MAX_LP_COUNT); // 1024 - out of range
        mask.add(u32::MAX as usize); // far out of range
        assert!(!mask.contains(AffinityMask::MAX_LP_COUNT));
        assert_eq!(mask.count(), 1);
    }
}