Re: [PATCH v3] rust: clist: Add support to interface with C linked lists

Joel Fernandes
2025-12-01T20:57:23Z

On 12/1/2025 3:32 PM, Joel Fernandes wrote:
> On 11/30/2025 7:34 PM, John Hubbard wrote:

[...]

>>> +/// Refer to the examples in the [crate::clist] module documentation.
>>> +#[macro_export]
>>> +macro_rules! clist_create {
>>> + ($head:expr, $rust_type:ty, $c_type:ty, $field:ident) => {
>>> + $crate::clist::Clist::<$rust_type>::from_raw_and_offset::<
>>> + { ::core::mem::offset_of!($c_type, $field) },
>>> + >($head)
>>> + };
>>> +}
>>
>> Unlike the corresponding C container_of() macro, this one here has no
>> compile-time verification that the field is actually a list_head.
>>
>> How about this, to add that check:
>>
>> --- a/rust/kernel/clist.rs
>> +++ b/rust/kernel/clist.rs
>> macro_rules! clist_create {
>> - ($head:expr, $rust_type:ty, $c_type:ty, $field:ident) => {
>> - $crate::clist::Clist::<$rust_type>::from_raw_and_offset::<
>> + ($head:expr, $rust_type:ty, $c_type:ty, $field:ident) => {{
>> + // Compile-time check: $field must be a list_head.
>> + const _: () = {
>> + let _check: fn(*const $c_type) -> *const $crate::bindings::list_head =
>> + |p| unsafe { ::core::ptr::addr_of!((*p).$field) };
>> + };
>> + $crate::clist::Clist::<$rust_type, { ::core::mem::offset_of!($c_type, $field) }>::from_raw(
>> $head,
>> )
>> - };
>> + }};
>
> Sure I will play with your suggested snippet and add that, thanks.
I think it works also without the 'const _:' block:
let _: fn(*const $c_type) -> *const $crate::bindings::list_head =
|p| unsafe { ::core::ptr::addr_of!((*p).$field) };

I will roll that in, thanks John.

- Joel