1
+ use core:: fmt;
1
2
use core:: ptr;
2
3
3
4
use crate :: link:: Link ;
@@ -13,6 +14,21 @@ mod sealed {
13
14
impl < T > Sealed for Rc < T > { }
14
15
}
15
16
17
+ /// The error type for `try_adopt` methods.
18
+ ///
19
+ /// See [`Adopt::try_adopt`] for more information.
20
+ #[ derive( Debug , Clone , Copy , Hash , PartialEq , Eq , PartialOrd , Ord ) ]
21
+ pub struct AdoptError ( ( ) ) ;
22
+
23
+ #[ cfg( feature = "std" ) ]
24
+ impl std:: error:: Error for AdoptError { }
25
+
26
+ impl fmt:: Display for AdoptError {
27
+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
28
+ f. write_str ( "Rc adoption failed because the Rc does not own a pointer to the adoptee" )
29
+ }
30
+ }
31
+
16
32
/// Build a graph of linked [`Rc`] smart pointers to enable busting cycles on
17
33
/// drop.
18
34
///
@@ -34,12 +50,20 @@ mod sealed {
34
50
///
35
51
/// [`adopt_unchecked`]: Adopt::adopt_unchecked
36
52
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
37
- pub unsafe trait Adopt : sealed:: Sealed {
53
+ pub unsafe trait Adopt : sealed:: Sealed + Sized {
38
54
/// The smart pointer's inner owned value.
39
55
type Inner ;
40
56
41
57
/// TODO: document me!
42
- fn adopt ( this : & mut Self , other : & Self )
58
+ fn adopt ( this : & mut Self , other : & Self ) -> Self
59
+ where
60
+ Self :: Inner : Trace ,
61
+ {
62
+ Self :: try_adopt ( this, other) . unwrap_or_else ( |err| panic ! ( "{}" , err) )
63
+ }
64
+
65
+ /// TODO: document me!
66
+ fn try_adopt ( this : & mut Self , other : & Self ) -> Result < Self , AdoptError >
43
67
where
44
68
Self :: Inner : Trace ;
45
69
@@ -92,7 +116,7 @@ unsafe impl<T> Adopt for Rc<T> {
92
116
type Inner = T ;
93
117
94
118
/// TODO: document me!
95
- fn adopt ( this : & mut Self , other : & Self )
119
+ fn try_adopt ( this : & mut Self , other : & Self ) -> Result < Self , AdoptError >
96
120
where
97
121
Self :: Inner : Trace ,
98
122
{
@@ -125,6 +149,9 @@ unsafe impl<T> Adopt for Rc<T> {
125
149
unsafe {
126
150
Self :: adopt_unchecked ( this, & node) ;
127
151
}
152
+ Ok ( node)
153
+ } else {
154
+ Err ( AdoptError ( ( ) ) )
128
155
}
129
156
}
130
157
0 commit comments