[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <Z8hUIPtE_9P60fAf@google.com>
Date: Wed, 5 Mar 2025 13:39:44 +0000
From: Alice Ryhl <aliceryhl@...gle.com>
To: Oliver Mangold <oliver.mangold@...me>
Cc: Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>,
Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>,
"Björn Roy Baron" <bjorn3_gh@...tonmail.com>, Benno Lossin <benno.lossin@...ton.me>,
Andreas Hindborg <a.hindborg@...nel.org>, Trevor Gross <tmgross@...ch.edu>,
rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org
Subject: Re: [PATCH v4] rust: adding UniqueRefCounted and UniqueRef types
On Wed, Mar 05, 2025 at 11:31:44AM +0000, Oliver Mangold wrote:
> Add `UniqueRef` as a variant of `ARef` that is guaranteed to be unique.
> This is useful when mutable access to the underlying type is required
> and we can guarantee uniqueness, and when APIs that would normally take
> an `ARef` require uniqueness.
>
> Signed-off-by: Oliver Mangold <oliver.mangold@...me>
[...]
> +impl<T: UniqueRefCounted> Deref for UniqueRef<T> {
> + type Target = T;
> +
> + fn deref(&self) -> &Self::Target {
> + // SAFETY: The type invariants guarantee that the object is valid.
> + unsafe { self.ptr.as_ref() }
> + }
> +}
What stops people from doing this?
let my_unique: UniqueRef<T> = ...;
let my_ref: &T = &*my_unique;
let my_shared: ARef<T> = ARef::from(my_ref);
Now it is no longer unique.
> +impl<T: UniqueRefCounted> DerefMut for UniqueRef<T> {
> + fn deref_mut(&mut self) -> &mut Self::Target {
> + // SAFETY: The type invariants guarantee that the object is valid.
> + unsafe { self.ptr.as_mut() }
> + }
> +}
This DerefMut will make it almost impossible for C types to implement
UniqueRefCounted because it is incompatible with pinning. You probably
want `T: UniqueRefCounted + Unpin` here.
For `T: !Unpin` (i.e. almost all C types), you can at most produce an
`Pin<&mut Self>`.
Alice
Powered by blists - more mailing lists