Re: [PATCH v4] rust: kernel: introduce `unsafe_precondition_assert!` macro
From: Ritvik Gupta
Date: Tue Aug 12 2025 - 17:26:44 EST
> +/// # Examples
> +///
> +/// ```no_run
> +/// # use kernel::unsafe_precondition_assert;
> +/// # use kernel::cpu::{nr_cpu_ids, CpuId};
> +/// /// Creates a [`CpuId`] from the given `id` without bound checks.
> +/// ///
> +/// /// # Safety
> +/// ///
> +/// /// The caller must ensure that `id` is a valid CPU ID (i.e, `0 <= id < nr_cpu_ids()`).
> +/// unsafe fn new_cpu_id_unchecked(id: i32) -> CpuId {
> +/// let max_cpus = nr_cpu_ids();
> +///
> +/// unsafe_precondition_assert!(id >= 0, "id ({}) must be positive", id);
> +///
> +/// unsafe_precondition_assert!(
> +/// id < max_cpus, "id ({}) must be less than total CPUs ({})", id, max_cpus
> +/// );
> +///
> +/// CpuId(id)
> +/// }
> +/// ```
The example I've included is incorrect because `CpuId` inner field is private,
so it can't be constructed this way.
`CpuId::from_i32_unchecked()` exists, using it here would make the example a
trivial wrapper around that method, that would be unnecessary and confusing.
Also, I wasn't sure about the doctest config when I wrote it.
I'll send v5 with correct and much better example.
Plz ignore it. Sorry for the noise.