Re: [PATCH v4] rust: adding UniqueRefCounted and UniqueRef types

Alice Ryhl
2025-03-06T11:31:19Z

On Thu, Mar 06, 2025 at 10:14:05AM +0000, Oliver Mangold wrote:
> On 250306 0935, Alice Ryhl wrote:
> >
> > Ultimately, if a struct implements AlwaysRefcounted, then you can always
> > increments its refcount.
>
> > If you want a version of the struct where that
> > is not the case, then you need a different struct that does *not*
> > implement AlwaysRefcounted.
> >
> I guess so, but it would be possible to make 'From<&T> for ARef<T>' opt-in,
> by requiring a separate marker trait.
>
> That you can call 'AlwaysRefCounted::inc_ref()' directly doesn't seem a
> problem to me, as it will only leak the object, not create a reference.
>
> A quick grep shows me that there are currently 7 implementers:
>
> unsafe impl AlwaysRefCounted for Credential {
> unsafe impl AlwaysRefCounted for File {
> unsafe impl AlwaysRefCounted for LocalFile {
> unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
> unsafe impl crate::types::AlwaysRefCounted for Device {
> unsafe impl crate::types::AlwaysRefCounted for Task {
> unsafe impl AlwaysRefCounted for PidNamespace {
>
> So it looks doable to me.

How about this:

* Rename AlwaysRefCounted to RefCounted.
* Introduce a new AlwaysRefCounted trait with no methods and gate
`From<&T>` on it. It has RefCounted as a sub-trait.
* Introduce an Ownable trait with an Owned type like in [1].
* Given an Owned<T> where T:RefCounted you can convert from Owned<T> to
ARef<T>.

And there needs to be a safety requirement on Ownable or
AlwaysRefCounted which requires that a type cannot implement both
traits. Alternatively, if a type implements both, it needs to be safe to
have both Owned<T> and ARef<T> references at the same time, which could
make sense for a type that has one "special" reference and many normal
references.

If you want conversions ARef<T> to Owned<T>, you should add a new trait
TryIntoOwned that's a super-trait of both RefCounted and Owned and has
the `try` method for the conversion.

Thoughts?

Alice

[1]: https://lore.kernel.org/rust-for-linux/20250202-rust-page-v1-1-e3170d7fe55e@asahilina.net/