hwlocality 1.0.0-alpha.12

Idiomatic Rust bindings for the hwloc hardware locality library
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
//! Cache-specific attributes

use crate::{
    ffi::{int, transparent::TransparentNewtype},
    object::types::CacheType,
};
use hwlocality_sys::hwloc_cache_attr_s;
#[cfg(any(test, feature = "proptest"))]
use proptest::prelude::*;
#[allow(unused)]
#[cfg(test)]
use similar_asserts::assert_eq;
use std::{
    cmp::Ordering,
    ffi::c_uint,
    fmt::{self, Debug},
    hash::Hash,
    num::{NonZeroU64, NonZeroUsize},
};

/// Cache-specific attributes
#[derive(Copy, Clone, Eq, Hash, PartialEq)]
#[doc(alias = "hwloc_cache_attr_s")]
#[doc(alias = "hwloc_obj_attr_u::hwloc_cache_attr_s")]
#[repr(transparent)]
pub struct CacheAttributes(hwloc_cache_attr_s);
//
impl CacheAttributes {
    /// Size of the cache in bytes, if known
    #[doc(alias = "hwloc_cache_attr_s::size")]
    #[doc(alias = "hwloc_obj_attr_u::hwloc_cache_attr_s::size")]
    pub fn size(&self) -> Option<NonZeroU64> {
        NonZeroU64::new(self.0.size)
    }

    /// Depth of the cache (e.g. L1, L2, ...)
    ///
    /// Note that following hardware nomenclature, cache depths normally start
    /// at 1, corresponding to the L1 cache.
    #[doc(alias = "hwloc_cache_attr_s::depth")]
    #[doc(alias = "hwloc_obj_attr_u::hwloc_cache_attr_s::depth")]
    pub fn depth(&self) -> usize {
        int::expect_usize(self.0.depth)
    }

    /// Cache line size in bytes, if known
    #[doc(alias = "hwloc_cache_attr_s::linesize")]
    #[doc(alias = "hwloc_obj_attr_u::hwloc_cache_attr_s::linesize")]
    pub fn line_size(&self) -> Option<NonZeroUsize> {
        NonZeroUsize::new(int::expect_usize(self.0.linesize))
    }

    /// Ways of associativity
    #[doc(alias = "hwloc_cache_attr_s::associativity")]
    #[doc(alias = "hwloc_obj_attr_u::hwloc_cache_attr_s::associativity")]
    pub fn associativity(&self) -> CacheAssociativity {
        match self.0.associativity {
            -1 => CacheAssociativity::Full,
            0 => CacheAssociativity::Unknown,
            ways if ways > 0 => {
                let ways = c_uint::try_from(ways).expect("int > 0 -> uint can't fail");
                let ways = int::expect_usize(ways);
                let ways = NonZeroUsize::new(ways).expect("usize > 0 -> NonZeroUsize can't fail");
                CacheAssociativity::Ways(ways)
            }
            unexpected => unreachable!("got unexpected cache associativity {unexpected}"),
        }
    }

    /// Cache type
    #[doc(alias = "hwloc_cache_attr_s::type")]
    #[doc(alias = "hwloc_obj_attr_u::hwloc_cache_attr_s::type")]
    pub fn cache_type(&self) -> CacheType {
        // SAFETY: Cache attributes are not user-editable so we are sure this
        //         value comes from hwloc
        unsafe { CacheType::from_hwloc(self.0.ty) }
    }
}
//
#[cfg(any(test, feature = "proptest"))]
impl Arbitrary for CacheAttributes {
    type Parameters = ();
    type Strategy = prop::strategy::Map<
        (
            crate::strategies::IntSpecial0<u64>,
            crate::strategies::IntSpecial0<c_uint>,
            crate::strategies::IntSpecial0<c_uint>,
            prop::strategy::TupleUnion<(
                prop::strategy::WA<Just<std::ffi::c_int>>,
                prop::strategy::WA<std::ops::RangeInclusive<std::ffi::c_int>>,
                prop::strategy::WA<Just<std::ffi::c_int>>,
                prop::strategy::WA<std::ops::RangeInclusive<std::ffi::c_int>>,
            )>,
            crate::strategies::EnumRepr<hwlocality_sys::hwloc_obj_cache_type_t>,
        ),
        fn(
            (
                u64,
                c_uint,
                c_uint,
                std::ffi::c_int,
                hwlocality_sys::hwloc_obj_cache_type_t,
            ),
        ) -> Self,
    >;

    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
        use crate::strategies;
        use hwlocality_sys::hwloc_obj_cache_type_t;
        use std::ffi::c_int;

        // Biased RNGs ensuring reasonable odds of zero size/depth
        let size = strategies::u64_special0();
        let depth = strategies::uint_special0();
        let linesize = strategies::uint_special0();

        // Biased RNG ensuring reasonable associativity branch coverage
        let associativity = prop_oneof![
            1 => Just(0),  // Unknown associativity
            2 => 1..=c_int::MAX,  // N-ways associative
            1 => Just(-1),  // Fully associative
            1 => c_int::MIN..=-2  // Invalid associativity
        ];

        // Biased RNG ensuring reasonable valid/invalid cache type coverage
        let cache_type = strategies::enum_repr::<CacheType, hwloc_obj_cache_type_t>();

        // Put it all together
        (size, depth, linesize, associativity, cache_type).prop_map(
            |(size, depth, linesize, associativity, ty)| {
                Self(hwloc_cache_attr_s {
                    size,
                    depth,
                    linesize,
                    associativity,
                    ty,
                })
            },
        )
    }
}
//
impl Debug for CacheAttributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = f.debug_struct("CacheAttributes");

        debug
            .field("size", &self.size())
            .field("depth", &self.depth())
            .field("line_size", &self.line_size());

        if self.0.associativity >= -1 {
            debug.field("associativity", &self.associativity());
        } else {
            debug.field("associativity", &format!("{:?}", self.0.associativity));
        }

        debug.field("cache_type", &self.cache_type());

        debug.finish()
    }
}
//
// SAFETY: CacheAttributes is a repr(transparent) newtype of hwloc_cache_attr_s
unsafe impl TransparentNewtype for CacheAttributes {
    type Inner = hwloc_cache_attr_s;
}

/// Cache associativity
#[derive(Copy, Clone, Debug, Default, Eq, Hash, PartialEq)]
pub enum CacheAssociativity {
    /// Unknown associativity
    #[default]
    Unknown,

    /// N-ways associative
    Ways(NonZeroUsize),

    /// Fully associative
    Full,
}
//
#[cfg(any(test, feature = "proptest"))]
impl Arbitrary for CacheAssociativity {
    type Parameters = <NonZeroUsize as Arbitrary>::Parameters;
    type Strategy = prop::strategy::TupleUnion<(
        prop::strategy::WA<Just<Self>>,
        prop::strategy::WA<
            prop::strategy::Map<<NonZeroUsize as Arbitrary>::Strategy, fn(NonZeroUsize) -> Self>,
        >,
        prop::strategy::WA<Just<Self>>,
    )>;

    fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
        prop_oneof![
            1 => Just(Self::Unknown),
            3 => NonZeroUsize::arbitrary_with(args).prop_map(Self::Ways),
            1 => Just(Self::Full),
        ]
    }
}
//
impl PartialOrd for CacheAssociativity {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            (Self::Unknown, _) | (_, Self::Unknown) => None,
            (Self::Full, Self::Full) => Some(Ordering::Equal),
            (Self::Full, Self::Ways(_)) => Some(Ordering::Greater),
            (Self::Ways(_), Self::Full) => Some(Ordering::Less),
            (Self::Ways(x), Self::Ways(y)) => x.partial_cmp(y),
        }
    }
}

#[cfg(test)]
pub(super) mod tests {
    use super::*;
    use crate::{
        ffi::transparent::AsInner,
        object::{
            TopologyObject,
            attributes::{
                ObjectAttributes,
                tests::{ObjectsWithAttrs, object_pair},
            },
            depth::NormalDepth,
            types::ObjectType,
        },
        tests::assert_panics,
    };
    use hwlocality_sys::hwloc_obj_attr_u;
    #[allow(unused)]
    use similar_asserts::assert_eq;
    use static_assertions::{assert_impl_all, assert_not_impl_any};
    use std::{
        fmt::{Binary, Display, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex},
        io::{self, Read},
        ops::Deref,
        panic::UnwindSafe,
    };
    use strum::IntoEnumIterator;

    // Check that public types in this module keep implementing all expected
    // traits, in the interest of detecting future semver-breaking changes
    assert_impl_all!(CacheAssociativity:
        Copy, Debug, Default, Hash, PartialOrd, Sized, Sync, Unpin, UnwindSafe
    );
    assert_not_impl_any!(CacheAssociativity:
        Binary, Deref, Display, Drop, IntoIterator, LowerExp, LowerHex,
        Octal, Pointer, Read, UpperExp, UpperHex, fmt::Write, io::Write
    );
    assert_impl_all!(CacheAttributes:
        Copy, Debug, Hash, Sized, Sync, Unpin, UnwindSafe
    );
    assert_not_impl_any!(CacheAttributes:
        Binary, Default, Deref, Display, Drop, IntoIterator, LowerExp, LowerHex,
        Octal, PartialOrd, Pointer, Read, UpperExp, UpperHex, fmt::Write,
        io::Write
    );

    /// Pick a random CPU cache type
    fn cpu_cache_type() -> impl Strategy<Value = ObjectType> {
        let cache_types = ObjectType::iter()
            .filter(|ty| ty.is_cpu_cache())
            .collect::<Vec<_>>();
        prop::sample::select(cache_types)
    }

    proptest! {
        #[test]
        fn unary_cache(ty in cpu_cache_type(), cache_attr: CacheAttributes) {
            check_any_cache(&cache_attr)?;
            let mut raw_attr = hwloc_obj_attr_u {
                cache: cache_attr.0,
            };
            let ptr = &raw mut raw_attr;
            // SAFETY: Type is consistent with union variant, data is valid
            unsafe {
                prop_assert!(matches!(
                    ObjectAttributes::new(ty, &ptr),
                    Some(ObjectAttributes::Cache(attr)) if std::ptr::eq(attr.as_inner(), &raw const raw_attr.cache)
                ));
            }
        }
    }

    proptest! {
        #[test]
        fn binary_cache_associativity(assoc1: CacheAssociativity, assoc2: CacheAssociativity) {
            let ord = match (assoc1, assoc2) {
                (CacheAssociativity::Unknown, _) | (_, CacheAssociativity::Unknown) => None,
                (CacheAssociativity::Full, CacheAssociativity::Full) => Some(Ordering::Equal),
                (CacheAssociativity::Full, CacheAssociativity::Ways(_)) => Some(Ordering::Greater),
                (CacheAssociativity::Ways(_), CacheAssociativity::Full) => Some(Ordering::Less),
                (CacheAssociativity::Ways(x), CacheAssociativity::Ways(y)) => x.partial_cmp(&y),
            };
            prop_assert_eq!(assoc1.partial_cmp(&assoc2), ord);
        }
    }

    /// Pick a pair of CPU caches in the test topology if possible
    fn cache_pair() -> impl Strategy<Value = Option<[&'static TopologyObject; 2]>> {
        let caches = &ObjectsWithAttrs::instance().caches;
        object_pair(caches, caches)
    }

    proptest! {
        /// Check properties that should be true of any pair of CPU caches
        #[test]
        fn valid_cache_pair(cache_pair in cache_pair()) {
            if let Some(pair) = cache_pair {
                check_valid_cache_pair(pair)?;
            }
        }
    }

    /// Check [`CacheAttributes`] properties that should be true of valid
    /// [`TopologyObject`]s coming from hwloc
    pub(crate) fn check_valid_cache(attr: &CacheAttributes) -> Result<(), TestCaseError> {
        check_any_cache(attr)?;

        // True on every non-niche hardware architecture, which makes it a
        // reasonable data consistency check
        if let Some(linesize) = attr.line_size() {
            prop_assert!(linesize.is_power_of_two());
        }

        Ok(())
    }

    /// Check [`CacheAttributes`] properties that should always be true
    fn check_any_cache(attr: &CacheAttributes) -> Result<(), TestCaseError> {
        let hwloc_cache_attr_s {
            size,
            depth,
            linesize,
            associativity,
            ..
        } = attr.0;

        prop_assert_eq!(attr.size(), NonZeroU64::new(size));

        prop_assert_eq!(attr.depth(), usize::try_from(depth).unwrap());
        let depth_dbg = format!("{:?}", attr.depth());

        prop_assert_eq!(
            attr.line_size(),
            NonZeroUsize::new(usize::try_from(linesize).unwrap())
        );

        let assoc_dbg = if associativity < -1 {
            assert_panics(|| attr.associativity())?;
            format!("\"{associativity:?}\"")
        } else {
            match associativity {
                -1 => prop_assert_eq!(attr.associativity(), CacheAssociativity::Full),
                0 => prop_assert_eq!(attr.associativity(), CacheAssociativity::Unknown),
                positive => prop_assert_eq!(
                    attr.associativity(),
                    CacheAssociativity::Ways(
                        NonZeroUsize::new(usize::try_from(positive).unwrap()).unwrap()
                    )
                ),
            }
            format!("{:?}", attr.associativity())
        };

        let ty_dbg = format!("{:?}", attr.cache_type());

        prop_assert_eq!(
            format!("{attr:?}"),
            format!(
                "CacheAttributes {{ \
                    size: {:?}, \
                    depth: {}, \
                    line_size: {:?}, \
                    associativity: {}, \
                    cache_type: {} \
                }}",
                attr.size(),
                depth_dbg,
                attr.line_size(),
                assoc_dbg,
                ty_dbg
            )
        );

        Ok(())
    }

    /// Check attribute properties that should be true of any pair of valid CPU
    /// caches from the hwloc topology
    fn check_valid_cache_pair([cache1, cache2]: [&TopologyObject; 2]) -> Result<(), TestCaseError> {
        fn cache_depth(
            cache: &TopologyObject,
        ) -> Result<(NormalDepth, CacheAttributes), TestCaseError> {
            let res = if let Some(ObjectAttributes::Cache(attr)) = cache.attributes() {
                (cache.depth().expect_normal(), *attr)
            } else {
                prop_assert!(false, "Not a CPU cache");
                unreachable!()
            };
            Ok(res)
        }
        let (depth1, attr1) = cache_depth(cache1)?;
        let (depth2, attr2) = cache_depth(cache2)?;

        let obj_depth_cmp = depth1.cmp(&depth2);
        let cache_depth_cmp = attr2.depth().cmp(&attr1.depth());
        if attr1.cache_type() == attr2.cache_type() {
            prop_assert_eq!(obj_depth_cmp, cache_depth_cmp);
        } else {
            prop_assert!(cache_depth_cmp == obj_depth_cmp || cache_depth_cmp == Ordering::Equal);
        }

        prop_assert_eq!(
            attr1.associativity() == CacheAssociativity::Unknown,
            attr2.associativity() == CacheAssociativity::Unknown
        );

        Ok(())
    }
}