Re: [PATCH] rust: rbtree: fix cursor method lifetimes to match tree lifetime
From: Alice Ryhl
Date: Fri Nov 07 2025 - 04:27:32 EST
On Fri, Nov 7, 2025 at 6:07 AM Hang Shu <m18080292938@xxxxxxx> wrote:
>
> From: Hang Shu <hangshu847@xxxxxxxxx>
>
> The returned keys and values of cursor methods should be bound by
> the lifetime of the rbtree itself ('a), not the lifetime of the cursor.
>
> Without this adjustment, examples like the following fail to compile:
>
> fn test_rbtree_cursor(rbtree: &mut RBTree<i32, i32>) -> &i32 {
> rbtree.try_create_and_insert(1, 1, GFP_KERNEL).unwrap();
> let mut cursor = rbtree.cursor_front().unwrap();
> // compile error
> // cannot return value referencing local variable `cursor`
> cursor.peek_next().unwrap().1
> }
>
> This modification ensures that references to tree elements remain valid
> independently of the cursor's scope,
> aligning with the actual lifetime dependencies in the data structure.
>
> The changes will be applied to multiple similar methods
> throughout the Cursor implementation to maintain consistency.
>
> Fixes: 98c14e40e07a ("rust: rbtree: add cursor")
> Signed-off-by: Hang Shu <hangshu847@xxxxxxxxx>
> ---
> rust/kernel/rbtree.rs | 16 ++++++++--------
> 1 file changed, 8 insertions(+), 8 deletions(-)
>
> diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs
> index 9e178dacddf1..702a1b6ef7a9 100644
> --- a/rust/kernel/rbtree.rs
> +++ b/rust/kernel/rbtree.rs
> @@ -742,7 +742,7 @@ unsafe impl<'a, K: Sync, V: Sync> Sync for Cursor<'a, K, V> {}
>
> impl<'a, K, V> Cursor<'a, K, V> {
> /// The current node
> - pub fn current(&self) -> (&K, &V) {
> + pub fn current(&self) -> (&'a K, &'a V) {
> // SAFETY:
> // - `self.current` is a valid node by the type invariants.
> // - We have an immutable reference by the function signature.
> @@ -750,7 +750,7 @@ pub fn current(&self) -> (&K, &V) {
> }
>
> /// The current node, with a mutable value
> - pub fn current_mut(&mut self) -> (&K, &mut V) {
> + pub fn current_mut(&mut self) -> (&'a K, &'a mut V) {
This would allow me to call current_mut() twice on the same cursor to
get two mutable references to the same value. That is not okay.
If you want to have methods that return a reference with the tree's
lifetime instead of the cursor's, then you need to add new methods
(probably called into_*) rather than modify the existing ones.
Alice