Re: [PATCH v4 4/6] rust: rbtree: add mutable iterator

From: Boqun Feng
Date: Mon Jun 03 2024 - 13:42:51 EST


On Mon, Jun 03, 2024 at 04:05:19PM +0000, Matt Gilbride wrote:
[...]
> +/// A mutable iterator over the nodes of a [`RBTree`].
> +///
> +/// Instances are created by calling [`RBTree::iter_mut`].
> +pub struct IterMut<'a, K, V> {
> + _tree: PhantomData<&'a mut RBTree<K, V>>,
> + iter_raw: IterRaw<K, V>,
> +}
> +
> +// SAFETY: The [`RBTreeIterator`] gives out mutable references to K and V, so it has the same

s/RBTreeIterator/IterMut ?

Also `IterMut` doesn't give out mutable references to K, which makes
me think...

> +// thread safety requirements as mutable references.
> +unsafe impl<'a, K: Send, V: Send> Send for IterMut<'a, K, V> {}
> +

we can lose the constrains to `K: Sync`, right?

Regards,
Boqun

> +// SAFETY: The [`RBTreeIterator`] gives out mutable references to K and V, so it has the same
> +// thread safety requirements as mutable references.
> +unsafe impl<'a, K: Sync, V: Sync> Sync for IterMut<'a, K, V> {}
> +
> +impl<'a, K, V> Iterator for IterMut<'a, K, V> {
> + type Item = (&'a K, &'a mut V);
> +
> + fn next(&mut self) -> Option<Self::Item> {
> + self.iter_raw.next().map(|(k, v)|
> + // SAFETY: Due to `&mut self`, we have exclusive access to `k` and `v`, for the lifetime of `'a`.
> + unsafe { (&*k, &mut *v) })
> + }
> +}
> +
[...]