### first_set example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to use Bitmap::first_set() to get the first set index. The example asserts that a new bitmap returns None, a range returns the start, and a full bitmap returns Some(0). ```rust use hwlocality::bitmap::Bitmap; let first_set_usize = |b: Bitmap| b.first_set().map(usize::from); assert_eq!(Bitmap::new().first_set(), None); assert_eq!(first_set_usize(Bitmap::from_range(12..=34)), Some(12)); assert_eq!(first_set_usize(Bitmap::full()), Some(0)); ``` -------------------------------- ### Example for partition_point Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Example demonstrating the partition_point method to find the index of the partition point. ```rust let v = [1, 2, 3, 3, 5, 6, 7]; let i = v.partition_point(|&x| x < 5); ``` -------------------------------- ### Example for is_sorted_by_key Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Example demonstrating the is_sorted_by_key method with key extraction functions. ```rust assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len())); assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs())); ``` -------------------------------- ### get example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to use get with a position or a range to get a reference to an element or subslice. Returns None if out of bounds. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### first_unset example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to use Bitmap::first_unset() to get the first unset index. The example asserts that a new bitmap returns Some(0), a range starting at 0 returns the end, and a full bitmap returns None. ```rust use hwlocality::bitmap::Bitmap; let first_unset_usize = |b: Bitmap| b.first_unset().map(usize::from); assert_eq!(first_unset_usize(Bitmap::new()), Some(0)); assert_eq!(first_unset_usize(Bitmap::from_range(..12)), Some(12)); assert_eq!(Bitmap::full().first_unset(), None); ``` -------------------------------- ### Example for basic_simd_sum Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Example code for a function basic_simd_sum, showing a vector of f32 numbers and an assertion. ```rust let numbers: Vec = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` -------------------------------- ### Example output of topology walk Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/index.html Possible output from the topology-walking example, showing objects at each depth from Machine down to PU. ```text *** Objects at depth 0 0: Machine *** Objects at depth 1 0: Package *** Objects at depth 2 0: L3 (16MB) *** Objects at depth 3 0: L2 (512KB) 1: L2 (512KB) 2: L2 (512KB) 3: L2 (512KB) 4: L2 (512KB) 5: L2 (512KB) *** Objects at depth 4 0: L1d (32KB) 1: L1d (32KB) 2: L1d (32KB) 3: L1d (32KB) 4: L1d (32KB) 5: L1d (32KB) *** Objects at depth 5 0: Core 1: Core 2: Core 3: Core 4: Core 5: Core *** Objects at depth 6 0: PU 1: PU 2: PU 3: PU 4: PU 5: PU 6: PU 7: PU 8: PU 9: PU 10: PU 11: PU ``` -------------------------------- ### Example for is_sorted Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Example demonstrating the is_sorted method on slices, including empty and NaN cases. ```rust let empty: [i32; 0] = []; assert!([1, 2, 2, 9].is_sorted()); assert!(![1, 3, 2, 4].is_sorted()); assert!([0].is_sorted()); assert!(empty.is_sorted()); assert!(![0.0, 1.0, f32::NAN].is_sorted()); ``` -------------------------------- ### Example for is_sorted_by Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Example demonstrating the is_sorted_by method with custom comparator functions. ```rust assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b)); assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b)); assert!([0].is_sorted_by(|a, b| true)); assert!([0].is_sorted_by(|a, b| false)); let empty: [i32; 0] = []; assert!(empty.is_sorted_by(|a, b| false)); assert!(empty.is_sorted_by(|a, b| true)); ``` -------------------------------- ### last_unset example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to use Bitmap::last_unset() to get the last unset index. The example asserts that a new bitmap returns None, a range starting at 12 returns 11, and a full bitmap returns None. ```rust use hwlocality::bitmap::Bitmap; let last_unset_usize = |b: Bitmap| b.last_unset().map(usize::from); assert_eq!(Bitmap::new().last_unset(), None); assert_eq!(last_unset_usize(Bitmap::from_range(12..)), Some(11)); assert_eq!(Bitmap::full().last_unset(), None); ``` -------------------------------- ### Topology implementation block with documentation Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/object/hierarchy.rs.html Starts the implementation block for Topology with documentation about object levels, depths, and types. Points to upstream hwloc documentation for terms and definitions. ```rust /// # Object levels, depths and types /// /// Be sure to see read through the /// [Terms and Definitions](https://hwloc.readthedocs.io/en/stable/termsanddefs.html) /// section of the upstream hwloc documentation to avoid any confusion about /// depths, child/sibling/cousin relationships, and see an example of an /// asymmetric topology where one package has fewer caches than its peers. // // --- Implementation details --- // // Upstream docs: https://hwloc.readthedocs.io/en/stable/group__hwlocality__levels.html // Also includes https://hwloc.readthedocs.io/en/stable/group__hwlocality__helper__find__cache.html, // which had to be reimplemented because it's static. impl Topology { ``` -------------------------------- ### Display formatting example for TopologyObject Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/object/mod.rs.html Shows how to use the Display implementation, which is more concise than Debug, using shorter type names and only major attributes. The example prints the root object of a test topology. ```rust /// # Example /// /// ```rust /// # use hwlocality::Topology; /// # let topology = Topology::test_instance(); /// println!("Root object: {}", topology.root_object()); /// # Ok::<_, eyre::Report>(()) /// ``` fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.display(f, false) } ``` -------------------------------- ### Range iterator next() examples Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Example for the `Range` iterator, showing successive `next()` calls returning `Some(Range)` values with increasing start and end indices. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 1 })); assert_eq!(iter.next(), Some(Range { start: 3, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 6, end: 7 })); assert_eq!(iter.next(), Some(Range { start: 9, end: 10 })); ``` -------------------------------- ### trim_start_matches() examples Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Demonstrates trim_start_matches() with a char and a function pattern, removing only leading matches. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); ``` -------------------------------- ### Topology::depth_for_type() documentation and example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/object/hierarchy.rs.html Starts the documentation and example for `depth_for_type()`, which returns the depth for a given `ObjectType`. Lists possible errors: `TypeToDepthError::Nonexistent` and `TypeToDepthError::Multiple` (e.g., for `Group`). The example retrieves the depth for `ObjectType::Machine`. ```rust /// Depth for the given [`ObjectType`] /// /// # Errors /// /// - [`TypeToDepthError::Nonexistent`] if no object of this type is present or /// if the OS doesn't provide this kind of information. If a similar type /// is acceptable, consider using [`depth_or_below_for_type()`] or /// [`depth_or_above_for_type()`] instead. /// - [`TypeToDepthError::Multiple`] if objects of this type exist at multiple /// depths (can happen when `object_type` is [`Group`]). /// /// # Examples /// /// ``` /// # use hwlocality::object::types::ObjectType; /// # /// # let topology = hwlocality::Topology::test_instance(); /// # /// let machine_depth = topology.depth_for_type(ObjectType::Machine)?; ``` -------------------------------- ### Create a full Bitmap with Bitmap::full() Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Creates a full Bitmap. The example asserts that the new bitmap is full. ```rust use hwlocality::bitmap::Bitmap; let full = Bitmap::full(); assert!(full.is_full()); ``` -------------------------------- ### depth_for_cache usage example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/object/hierarchy.rs.html Shows how to use depth_for_cache to get the depth of the L1 data cache. The example creates a test topology and asserts that the returned depth is Ok. ```rust # use hwlocality::object::types::CacheType; # let topology = hwlocality::Topology::test_instance(); let l1d_depth = topology.depth_for_cache(1, Some(CacheType::Data)); assert!(l1d_depth.is_ok()); # Ok::<(), eyre::Report>(()) ``` -------------------------------- ### TopologyBuilder::new() Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/topology/builder.rs.html Starts building a new Topology. This method initializes a new topology builder with default settings. ```APIDOC ## TopologyBuilder::new() ### Description Starts building a new Topology. This method initializes a new topology builder with default settings. ### Method Constructor ### Signature ```rust pub fn new() -> Self ``` ### Parameters None ### Returns - `Self` - A new `TopologyBuilder` instance. ### Example ```rust let builder = TopologyBuilder::new(); ``` ``` -------------------------------- ### Example: binding current thread to first two cores Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to compute a CPU binding bitmap from the CPUsets of the first two cores and bind the current thread, with a fallback for platforms without Core objects and a check for CPU binding support. ```rust // We want Cores, but we tolerate PUs on platforms that don't expose Cores // (either there are no hardware threads or hwloc could not detect them) let core_depth = topology.depth_or_below_for_type(ObjectType::Core)?; // Yields the first two cores of a multicore system, or // the only core of a single-core system let cores = topology.objects_at_depth(core_depth).take(2); // Compute the union of these cores' CPUsets, that's our CPU binding bitmap let set = cores.fold( CpuSet::new(), |acc, core| { acc | core.cpuset().expect("Cores should have CPUsets") } ); // Only actually bind if the platform supports it (macOS notably doesn't) if topology.supports(FeatureSupport::cpu_binding, CpuBindingSupport::set_thread) { topology.bind_cpu(&set, CpuBindingFlags::THREAD)?; } ``` -------------------------------- ### iter_unset example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to use Bitmap::iter_unset() to iterate over unset indices. The example collects the unset indices from a range starting at 12 and asserts they match the expected list. ```rust use hwlocality::bitmap::Bitmap; let bitmap = Bitmap::from_range(12..); let indices = bitmap.iter_unset().map(usize::from).collect::>(); assert_eq!(indices, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); ``` -------------------------------- ### last_set example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to use Bitmap::last_set() to get the last set index. The example asserts that a new bitmap returns None, a range returns the end, and a full bitmap returns None. ```rust use hwlocality::bitmap::Bitmap; let last_set_usize = |b: Bitmap| b.last_set().map(usize::from); assert_eq!(Bitmap::new().last_set(), None); assert_eq!(last_set_usize(Bitmap::from_range(12..=34)), Some(34)); assert_eq!(Bitmap::full().last_set(), None); ``` -------------------------------- ### str::starts_with examples Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Demonstrates `str::starts_with` with a `&str` pattern and with a slice of `char`s. The second example shows that a slice of `char`s is checked against the first character only, so both assertions succeed. ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` -------------------------------- ### get_mut example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to use get_mut to get a mutable reference to an element. Returns None if out of bounds. ```rust let x = &mut [0, 1, 2]; if let Some(elem) = x.get_mut(1) { *elem = 42; } assert_eq!(x, &[0, 42, 2]); ``` -------------------------------- ### write_with example (nightly maybe_uninit_fill) Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Example for the nightly-only `write_with` method on `[MaybeUninit]`. Requires the `maybe_uninit_fill` feature. Fills the slice using a closure that receives each index; panics if the closure panics. ```rust #![feature(maybe_uninit_fill)] use std::mem::MaybeUninit; let mut buf = [const { MaybeUninit::::uninit() }; 5]; let initialized = buf.write_with(|idx| idx + 1); assert_eq!(initialized, &mut [1, 2, 3, 4, 5]); ``` -------------------------------- ### str::get subslice example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Demonstrates `str::get` to safely get a subslice of a string without panicking. The example shows that valid ranges return `Some`, while indices that are not on UTF-8 boundaries or are out of bounds return `None`. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### windows() usage examples Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Illustrates window iteration over a slice, returning overlapping contiguous windows of length 3. Includes a case where the slice is shorter than the window size. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.windows(3); assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']); assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']); assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']); assert!(iter.next().is_none()); ``` ```Rust let slice = ['f', 'o', 'o']; let mut iter = slice.windows(4); assert!(iter.next().is_none()); ``` ```Rust use std::cell::Cell; let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5']; let slice = &mut array[..]; let slice_of_cells: &[Cell] = Cell::from_mut(slice).as_slice_of_cells(); for w in slice_of_cells.windows(3) { Cell::swap(&w[0], &w[2]); } assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']); ``` -------------------------------- ### str::is_char_boundary example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Shows how to use `str::is_char_boundary` to check if a byte index is a valid UTF-8 character boundary. The example asserts that the start, the boundary at byte 6, and the end are boundaries, while byte 2 and byte 8 are not. ```rust let s = "Löwe 老虎 Léopard"; assert!(s.is_char_boundary(0)); // start of `老` assert!(s.is_char_boundary(6)); assert!(s.is_char_boundary(s.len())); // second byte of `ö` assert!(!s.is_char_boundary(2)); // third byte of `老` assert!(!s.is_char_boundary(8)); ``` -------------------------------- ### get_unchecked example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to use get_unchecked to get a reference without bounds checking. Calling with an out-of-bounds index is undefined behavior. ```rust let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ``` -------------------------------- ### starts_with example: check prefix Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Returns true if needle is a prefix of the slice or equal to the slice. Always true for empty needle. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` -------------------------------- ### is_full example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Checks if all indices are set. ```rust use hwlocality::bitmap::Bitmap; assert!(!Bitmap::new().is_full()); assert!(!Bitmap::from_range(12..=34).is_full()); assert!(Bitmap::full().is_full()); ``` -------------------------------- ### depth_or_above_for_type usage example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/object/hierarchy.rs.html Shows how to use depth_or_above_for_type to get the depth of the first level at or above a given object type (e.g., Core) and compare it with the depth of a specific type (e.g., PU). The example asserts that the core-or-above depth is less than the PU depth. ```rust /// # let topology = hwlocality::Topology::test_instance(); /// # /// let pu_depth = topology.depth_for_type(ObjectType::PU)?; /// let core_or_above = topology.depth_or_below_for_type(ObjectType::Core)?; /// /// assert!(core_or_above.expect_normal() < pu_depth.expect_normal()); /// # /// # Ok::<(), eyre::Report>(()) ``` -------------------------------- ### str::len byte length example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Shows how to use `str::len` to get the byte length of a string. The example asserts that "foo" has length 3 and that "ƒoo" has length 4 bytes but only 3 characters. ```rust let len = "foo".len(); assert_eq!(3, len); assert_eq!("ƒoo".len(), 4); // fancy f! assert_eq!("ƒoo".chars().count(), 3); ``` -------------------------------- ### Create a Topology with custom BuildFlags using Topology::builder() Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/topology/mod.rs.html Prepares a TopologyBuilder for custom configuration. The example shows setting BuildFlags::INCLUDE_DISALLOWED and verifying the build flags after building. Returns a Result that may fail with RawHwlocError. ```rust /// Prepare to create a Topology with custom configuration /// /// # Examples /// /// ``` /// # use hwlocality::topology::{Topology, builder::BuildFlags}; /// let flags = BuildFlags::INCLUDE_DISALLOWED; /// let topology = Topology::builder().with_flags(flags)?.build()?; /// assert_eq!(topology.build_flags(), flags); /// # Ok::<(), eyre::Report>(()) /// ``` #[doc(alias = "hwloc_topology_init")] pub fn builder() -> TopologyBuilder { TopologyBuilder::new() } ``` -------------------------------- ### get_unchecked_mut example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to use get_unchecked_mut to get a mutable reference without bounds checking. Calling with an out-of-bounds index is undefined behavior. ```rust let x = &mut [1, 2, 4]; unsafe { let elem = x.get_unchecked_mut(1); *elem = 13; } assert_eq!(x, &[1, 13, 4]); ``` -------------------------------- ### Compute CPU set from cores and bind thread Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/bitmap/mod.rs.html Shows how to build a CpuSet by folding over the CPUsets of the first two cores and bind the current thread if the platform supports it. Uses hwlocality's Topology, CpuSet, ObjectType, and CpuBindingFlags. The example returns an eyre::Report on error. ```rust /// [`TopologyObject`]s and combine them through boolean operations. For /// instance, binding the current thread on a pair of cores may be performed /// with: /// /// ``` /// # use hwlocality::{ /// # cpu::{binding::CpuBindingFlags, cpuset::CpuSet}, /// # object::{types::ObjectType}, /// # topology::support::{CpuBindingSupport, FeatureSupport}, /// # }; /// # /// # let topology = hwlocality::Topology::test_instance(); /// # /// // We want Cores, but we tolerate PUs on platforms that don't expose Cores /// // (either there are no hardware threads or hwloc could not detect them) /// let core_depth = topology.depth_or_below_for_type(ObjectType::Core)?; /// /// // Yields the first two cores of a multicore system, or /// // the only core of a single-core system /// let cores = topology.objects_at_depth(core_depth).take(2); /// /// // Compute the union of these cores' CPUsets, that's our CPU binding bitmap /// let set = cores.fold( /// CpuSet::new(), /// |acc, core| { acc | core.cpuset().expect("Cores should have CPUsets") } /// ); /// /// // Only actually bind if the platform supports it (macOS notably doesn't) /// if topology.supports(FeatureSupport::cpu_binding, CpuBindingSupport::set_thread) { /// topology.bind_cpu(&set, CpuBindingFlags::THREAD)?; /// } /// # /// # Ok::<(), eyre::Report>(()) /// ``` ``` -------------------------------- ### element_offset basic usage Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to get the index of an element reference using `element_offset`. Returns `Some(index)` when the element points to the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` -------------------------------- ### last_chunk example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to use last_chunk::() to get a reference to the last N elements as an array. Returns None if the slice is shorter than N. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### Topology::new() Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/topology/mod.rs.html Creates a new Topology instance using default build configuration. This is the main entry point for obtaining a logical representation of the physical hardware. ```APIDOC ## Topology::new() ### Description Creates a new Topology instance using default build configuration. This is the main entry point for obtaining a logical representation of the physical hardware. ### Method new ### Signature pub fn new() -> Result ### Parameters None ### Return Value - **Result** - A new Topology instance on success, or a RawHwlocError on failure. ### Example ```rust # use hwlocality::Topology; let topology = Topology::new()?; # Ok::<(), eyre::Report>(()) ``` ``` -------------------------------- ### as_rchunks example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Splits a slice into N-element chunks starting from the end, with a remainder at the beginning. The remainder length is slice.len() % N. Panics if N is zero. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### weight example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/struct.Bitmap.html Shows how to use Bitmap::weight() to count set indices. The example asserts that a new bitmap has weight 0, a range has the difference, and a full bitmap returns None. ```rust use hwlocality::bitmap::Bitmap; assert_eq!(Bitmap::new().weight(), Some(0)); assert_eq!(Bitmap::from_range(12..34).weight(), Some(34-12)); assert_eq!(Bitmap::full().weight(), None); ``` -------------------------------- ### Get depth for ObjectType::Package or below and compare with machine depth Source: https://docs.rs/hwlocality/1.0.0-alpha.12/src/hwlocality/object/hierarchy.rs.html Demonstrates using `depth_or_below_for_type` to get the depth of a Package object or below, and compares it with the machine depth. The example asserts that the machine depth is less than the package-or-below depth. Requires a topology instance and uses the `?` operator to propagate errors. ```rust # use hwlocality::{object::types::ObjectType}; # # let topology = hwlocality::Topology::test_instance(); # let machine_depth = topology.depth_for_type(ObjectType::Machine)?; let package_or_below = topology.depth_or_below_for_type(ObjectType::Package)?; assert!(machine_depth.expect_normal() < package_or_below.expect_normal()); # # Ok::<(), eyre::Report>(()) ``` -------------------------------- ### split_last_chunk example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to use split_last_chunk::<2>() to get the last two elements as an array and the remaining slice. Returns None if the slice is shorter than N. ```rust let x = &[0, 1, 2]; if let Some((elements, last)) = x.split_last_chunk::<2>() { assert_eq!(elements, &[0]); assert_eq!(last, &[1, 2]); } assert_eq!(None, x.split_last_chunk::<4>()); ``` -------------------------------- ### Print complete CPU set of root object (complete_cpuset) Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/object/struct.TopologyObject.html Example from the complete_cpuset() method documentation. Prints the complete CPU set of the root object using topology.root_object().complete_cpuset(). ```rust println!( "Overall CPUs attached to the root object: {:?}", topology.root_object().complete_cpuset() ); ``` -------------------------------- ### pow example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/bitmap/type.BitmapIndex.html Shows how to use pow on PositiveInt to raise to a power using exponentiation by squaring. ```rust assert_eq!( PositiveInt::ZERO.pow(0), PositiveInt::ONE ); assert_eq!( PositiveInt::ONE.pow(3), PositiveInt::ONE ); assert_eq!( PositiveInt::MAX.pow(1), PositiveInt::MAX ); ``` -------------------------------- ### str::as_ptr example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/topology/export/xml/struct.XML.html Shows how to use `str::as_ptr` to get a raw pointer to the first byte of a string slice. The pointer must never be written to. ```rust let s = "Hello"; let ptr = s.as_ptr(); ``` -------------------------------- ### array_windows example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Shows how to iterate over overlapping windows of size N using array_windows. Panics if N is zero. ```rust let slice = [0, 1, 2, 3]; let mut iter = slice.array_windows(); assert_eq!(iter.next().unwrap(), &[0, 1]); assert_eq!(iter.next().unwrap(), &[1, 2]); assert_eq!(iter.next().unwrap(), &[2, 3]); assert!(iter.next().is_none()); ``` -------------------------------- ### as_rchunks_mut example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Splits a mutable slice into N-element chunks starting from the end, with a remainder at the beginning. The remainder length is slice.len() % N. Panics if N is zero. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; let (remainder, chunks) = v.as_rchunks_mut(); remainder[0] = 9; for chunk in chunks { *chunk = [count; 2]; count += 1; } assert_eq!(v, &[9, 1, 1, 2, 2]); ``` -------------------------------- ### as_chunks_mut example Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/memory/binding/struct.Bytes.html Splits a mutable slice into N-element chunks starting from the beginning, with a remainder at the end. The remainder length is slice.len() % N. Panics if N is zero. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; let (chunks, remainder) = v.as_chunks_mut(); remainder[0] = 9; for chunk in chunks { *chunk = [count; 2]; count += 1; } assert_eq!(v, &[1, 1, 2, 2, 9]); ``` -------------------------------- ### CpuSet::new Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/cpu/cpuset/struct.CpuSet.html Creates an empty CpuSet bitmap. ```APIDOC ## CpuSet::new ### Description Creates an empty bitmap. ### Method `pub fn new() -> Self` ### Parameters None. ### Returns A new empty `CpuSet`. ### See Also `Bitmap::new`. ``` -------------------------------- ### Walk hardware topology and print objects (Rust) Source: https://docs.rs/hwlocality/1.0.0-alpha.12/hwlocality/index.html Sets up a Topology and iterates over all normal depths, printing each object. Uses eyre for error handling. The output shows a possible result on a 6-core machine. ```rust use hwlocality::{object::depth::NormalDepth, Topology}; fn main() -> eyre::Result<()> { let topology = Topology::new()?; for depth in NormalDepth::iter_range(NormalDepth::MIN, topology.depth()) { println!("*** Objects at depth {depth}"); for (idx, object) in topology.objects_at_depth(depth).enumerate() { println!("{idx}: {object}"); } } Ok(()) } ```