Re: [PATCH v5 5/6] rust: rbtree: add `RBTreeCursor`

From: Boqun Feng
Date: Tue Jun 25 2024 - 15:50:55 EST


On Thu, Jun 06, 2024 at 02:50:08PM +0000, Matt Gilbride wrote:
[...]
> +impl<'a, K, V> RBTreeCursor<'a, K, V> {
[...]
> + /// SAFETY:
> + /// - `node` must be a valid pointer to a node in an [`RBTree`].
> + /// - The caller has immutable access to `node` for the duration of 'a.
> + unsafe fn to_key_value(node: *mut bindings::rb_node) -> (&'a K, &'a V) {

I think the function sigurature should be:

unsafe fn to_key_value<'b>(node: *mut bindings::rb_node) -> (&'b K, &'b V)

right? At least it's more clear to me. Ditto for the other two functions
below.

> + // SAFETY: the caller guarantees that `node` is a valid pointer in an `RBTree`.
> + let (k, v) = unsafe { Self::to_key_value_raw(node) };
> + // SAFETY: the caller guarantees immutable access to `node`.
> + (k, unsafe { &*v })
> + }
> +
> + /// SAFETY:
> + /// - `node` must be a valid pointer to a node in an [`RBTree`].
> + /// - The caller has mutable access to `node` for the duration of 'a.
> + unsafe fn to_key_value_mut(node: *mut bindings::rb_node) -> (&'a K, &'a mut V) {
> + // SAFETY: the caller guarantees that `node` is a valid pointer in an `RBTree`.
> + let (k, v) = unsafe { Self::to_key_value_raw(node) };
> + // SAFETY: the caller guarantees mutable access to `node`.
> + (k, unsafe { &mut *v })
> + }
> +
> + /// SAFETY:
> + /// - `node` must be a valid pointer to a node in an [`RBTree`].
> + /// - The caller has immutable access to the key for the duration of 'a.
> + unsafe fn to_key_value_raw(node: *mut bindings::rb_node) -> (&'a K, *mut V) {
> + // SAFETY: By the type invariant of `Self`, all non-null `rb_node` pointers stored in `self`
> + // point to the links field of `Node<K, V>` objects.
> + let this = unsafe { container_of!(node, Node<K, V>, links) }.cast_mut();
> + // SAFETY: The passed `node` is the current node or a non-null neighbor,
> + // thus `this` is valid by the type invariants.
> + let k = unsafe { &(*this).key };
> + // SAFETY: The passed `node` is the current node or a non-null neighbor,
> + // thus `this` is valid by the type invariants.
> + let v = unsafe { addr_of_mut!((*this).value) };
> + (k, v)
> + }
[...]