Add is_unique(), try_unwrap(), try_get_mut() to alloc::rc

Add a few new free functions to alloc::rc for manipulating
uniquely-owned Rc values. is_unique() can be used to test if the Rc is
uniquely-owned, try_unwrap() can remove the value from a uniquely-owned
Rc, and try_get_mut() can return a &mut for a uniquely-owned Rc.

These are all free functions, because smart pointers should avoid having
methods when possible. They can't be static methods because UFCS will
remove that distinction. I think we should probably change downgrade()
and make_unique() into free functions as well, but that's out of scope.
@aturon Possibly doesn't make a lot of sense out of context:
https://github.com/gfx-rs/gfx-rs/pull/144#issuecomment-50442985


Essentially you want an affine handle type that, for performance reasons,
can't really have a useful destructor, and the only way to share it is
behind `Rc` (or another shared container), but in the interest of not
having referring to values that no longer exist, removing the value from
the container requires the handle by-value, but you can't get that without
`try_unwrap`. It moves the failure into the user who is sharing the handle,
rather than having a handle which refers to a nonexistent value.


On Wed, Jul 30, 2014 at 10:04 AM, Kevin Ballard <notifications@github.com>
wrote:

> In src/liballoc/rc.rs:
>
> > +    }
> > +}
> > +
> > +/// Returns a mutable reference to the contained value if the `Rc` has
> > +/// unique ownership.
> > +///
> > +/// Returns `None` if the `Rc` does not have unique ownership.
> > +///
> > +/// # Example:
> > +///
> > +/// ```
> > +/// let mut x = Rc::new(3u);
> > +/// *Rc.try_get_mut(&mut x).unwrap() = 4u;
> > +/// assert_eq!(*x, 4u);
> > +/// let _y = x.clone();
> > +/// assert!(Rc.try_get_mut(&mut x).is_none());
>
> You're right, I guess I never ran the doc tests after changing to free
> functions.
>
> —
> Reply to this email directly or view it on GitHub
> <https://github.com/rust-lang/rust/pull/16101/files#r15597313>.
>



-- 
http://octayn.net/