Skip to content

ACP: Add methods to get reference counts from raw pointers to Arc\Rc #792

@loreball

Description

@loreball

Proposal

Problem statement

Arc and Rc provide increment_strong_count and decrement_strong_count to manipulate the strong count from a raw pointer, but don't provide a way to read it.

Motivating examples or use cases

I'm writing a tagged pointer wrapping an Arc and while filling out it's API I noticed I can't actually read the ref count easily. The current solution feels rather iffy.

struct SmartPointer<T> {
    pointer: *const T,
    phantom: PhantomData<Arc<T>>,
}

impl<T> SmartPointer<T> {
   const FLAG: usize = 0x1;
   /// val must have an align of at least 2 
   pub fn new(val: T) -> Self {
       assert!(core::mem::align_of::<T>() >= 2);
       let arc = Arc::new(val);

       Self {
           pointer: Arc::into_raw(arc).map_addr(|addr| addr | Self::FLAG),
           phantom: PhantomData
       }
   }
  
  pub fn strong_count(slf: &Self) -> usize {
      let addr = slf.pointer.map_addr(|addr| addr & !Self::FLAG);

      // SAFETY: The address came from `Arc::into_raw` and we don't drop this instance of the arc. 
      let arc = unsafe { Arc::from_raw(addr) };
      // don't drop this
      let arc = ManuallyDrop::new(arc);

      Arc::strong_count(&*arc)
  }
}

Solution sketch

impl<T: ?Sized, A: Allocator> Arc<T, A> {
    /// Get the number of strong (`Arc`) pointers from a raw pointer
    /// 
    /// This method does not consume or drop the arc behind this pointer. To prevent a memory leak
    /// the pointer must be converted back to an `Arc` using `Arc::from_raw` or the memory must be released
    /// using `Arc::decrement_strong_count`.
    /// 
    /// # Safety
    /// The raw pointer must have been previously returned from a call to `Arc::into_raw` and  associated `Arc` 
    /// instance must be valid (i.e. the strong count must be at least 1) for the duration of this method.
    pub unsafe fn strong_count_from_raw(ptr: *const T) -> usize {
        todo!()
    }
}

impl<T: ?Sized, A: Allocator> Rc<T, A> {
    /// Get the number of strong (`Rc`) pointers from a raw pointer
    /// 
    /// This method does not consume or drop the rc behind this pointer. To prevent a memory leak
    /// the pointer must be converted back to an `Rc` using `Rc::from_raw` or the memory must be released
    /// using `Rc::decrement_strong_count`.
    /// 
    /// # Safety
    /// The raw pointer must have been previously returned from a call to `Rc::into_raw`.
    pub unsafe fn strong_count_from_raw(ptr: *const T) -> usize {
        todo!()
    }
}

Alternatives

We can, of course, ignore this. One could always construct an arc from their pointer and read the strong count from that. This is error prone. Along with the existing API contract, one would also have to make sure they don't drop their temporary arc.

Links and related work

I wasn't able to find previous references to this issue but here's a link to the original tracking issue for increment_strong_count and friends rust-lang/rust#71983. And here's the original motivation for adding those methods rust-lang/rust#68700 (comment).

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions