binary_tree/
unbox.rs

1//! Pointer unboxing.
2
3use std::ptr;
4use std::rc::Rc;
5use std::sync::Arc;
6
7/// Trait specifying unboxing capability of a pointer type.
8pub trait Unbox {
9    type Target;
10
11    fn unbox(self) -> Self::Target;
12}
13
14impl<T> Unbox for Box<T>
15    where T: Sized
16{
17    type Target = T;
18
19    fn unbox(self) -> T {
20        unsafe { ptr::read(Box::into_raw(self)) }
21    }
22}
23
24impl<T> Unbox for Rc<T>
25    where T: Clone
26{
27    type Target = T;
28
29    fn unbox(mut self) -> T {
30        Rc::make_mut(&mut self);
31        match Rc::try_unwrap(self) {
32            Ok(inner) => inner,
33            _ => unreachable!(),
34        }
35    }
36}
37
38impl<T> Unbox for Arc<T>
39    where T: Clone
40{
41    type Target = T;
42
43    fn unbox(mut self) -> T {
44        Arc::make_mut(&mut self);
45        match Arc::try_unwrap(self) {
46            Ok(inner) => inner,
47            _ => unreachable!(),
48        }
49    }
50}