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

From: Andreas Hindborg
Date: Mon Mar 03 2025 - 09:10:24 EST


"Oliver Mangold" <oliver.mangold@xxxxx> writes:

[...]

> +/// Types that are [`AlwaysRefCounted`] and can be safely converted to an [`UniqueRef`]
> +///
> +/// # Safety
> +///
> +/// Implementers must ensure that the methods of the trait
> +/// change the reference count of the underlying object such that:
> +/// - the uniqueness invariant is upheld, i.e. it is not possible
> +/// to obtain another reference by any means (other than through the [`UniqueRef`])
> +/// until the [`UniqueRef`] is dropped or converted to an [`ARef`].
> +/// - [`UniqueRefCounted::dec_ref`] correctly frees the underlying object.
> +/// - [`UniqueRefCounted::unique_to_shared`] set the reference count to the value
> +/// - that the returned [`ARef`] expects for an object with a single reference
> +/// in existence.
> +pub unsafe trait UniqueRefCounted: AlwaysRefCounted + Sized {
> + /// Checks if the [`ARef`] is unique and convert it
> + /// to an [`UniqueRef`] it that is that case.
> + /// Otherwise it returns again an [`ARef`] to the same
> + /// underlying object.
> + fn try_shared_to_unique(this: ARef<Self>) -> Result<UniqueRef<Self>, ARef<Self>>;

This could just be `try_into_unique`, since the type of `this` gives the
rest of the context.

> + /// Converts the [`UniqueRef`] into an [`ARef`].
> + fn unique_to_shared(this: UniqueRef<Self>) -> ARef<Self>;

Similarly, this could be `into_shared`.


Best regards,
Andreas Hindborg