Re: [PATCH] rust: num: bounded: add safety comment for Bounded::__new

Alice Ryhl
2025-12-01T10:12:29Z

On Mon, Dec 01, 2025 at 02:25:16PM +0800, Hsiu Che Yu wrote:
> The `__new` constructor only performs a bounds check and stores the
> value in the wrapper type. It does not perform any unsafe memory
> operations, so it does not need to be marked as `unsafe`.
>
> Reported-by: Miguel Ojeda <ojeda@kernel.org>
> Closes: https://github.com/Rust-for-Linux/linux/issues/1211
>
> Signed-off-by: Hsiu Che Yu <yu.whisper.personal@gmail.com>
> ---
> rust/kernel/num/bounded.rs | 3 +++
> 1 file changed, 3 insertions(+)
>
> diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs
> index f870080af8ac..cde1b8ba6880 100644
> --- a/rust/kernel/num/bounded.rs
> +++ b/rust/kernel/num/bounded.rs
> @@ -284,6 +284,9 @@ impl<T, const N: u32> Bounded<T, N>
> ///
> /// The caller remains responsible for checking, either statically or dynamically, that `value`
> /// can be represented as a `T` using at most `N` bits.
> + ///
> + /// **Note**: This function is not marked as `unsafe` because it performs no memory-unsafe
> + /// operations itself.

I disagree. For the same reasons as str::from_utf8_unchecked, this
should also be unsafe. It creates a value that violates invariants,
which may be used to trigger UB combined with other safe code.

Alice