@@ -29,12 +29,27 @@ pub trait Clone {
29
29
/// are copied to maintain uniqueness, while the contents of
30
30
/// managed pointers are not copied.
31
31
fn clone ( & self ) -> Self ;
32
+
33
+ /// Perform copy-assignment from `source`.
34
+ ///
35
+ /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
36
+ /// but can be overriden to reuse the resources of `a` to avoid unnecessary
37
+ /// allocations.
38
+ #[ inline( always) ]
39
+ fn clone_from ( & mut self , source : & Self ) {
40
+ * self = source. clone ( )
41
+ }
32
42
}
33
43
34
44
impl < T : Clone > Clone for ~T {
35
- /// Return a deep copy of the owned box.
45
+ /// Return a copy of the owned box.
36
46
#[ inline]
37
47
fn clone ( & self ) -> ~T { ~( * * self ) . clone ( ) }
48
+
49
+ /// Perform copy-assignment from `source` by reusing the existing allocation.
50
+ fn clone_from ( & mut self , source : & ~T ) {
51
+ * * self = ( * * source) . clone ( )
52
+ }
38
53
}
39
54
40
55
impl < T > Clone for @T {
@@ -118,16 +133,31 @@ extern_fn_clone!(A, B, C, D, E, F, G, H)
118
133
119
134
/// A trait distinct from `Clone` which represents "deep copies" of things like
120
135
/// managed boxes which would otherwise not be copied.
121
- pub trait DeepClone {
136
+ pub trait DeepClone : Clone {
122
137
/// Return a deep copy of the value. Unlike `Clone`, the contents of shared pointer types
123
138
/// *are* copied.
124
139
fn deep_clone ( & self ) -> Self ;
140
+
141
+ /// Perform deep copy-assignment from `source`.
142
+ ///
143
+ /// `a.deep_clone_from(&b)` is equivalent to `a = b.deep_clone()` in
144
+ /// functionality, but can be overriden to reuse the resources of `a` to
145
+ /// avoid unnecessary allocations.
146
+ #[ inline( always) ]
147
+ fn deep_clone_from ( & mut self , source : & Self ) {
148
+ * self = source. deep_clone ( )
149
+ }
125
150
}
126
151
127
152
impl < T : DeepClone > DeepClone for ~T {
128
153
/// Return a deep copy of the owned box.
129
154
#[ inline]
130
155
fn deep_clone ( & self ) -> ~T { ~( * * self ) . deep_clone ( ) }
156
+
157
+ /// Perform deep copy-assignment from `source` by reusing the existing allocation.
158
+ fn deep_clone_from ( & mut self , source : & ~T ) {
159
+ * * self = ( * * source) . deep_clone ( )
160
+ }
131
161
}
132
162
133
163
// FIXME: #6525: should also be implemented for `T: Send + DeepClone`
@@ -234,6 +264,22 @@ fn test_borrowed_clone() {
234
264
assert_eq ! ( * z, 5 ) ;
235
265
}
236
266
267
+ #[ test]
268
+ fn test_clone_from ( ) {
269
+ let a = ~5 ;
270
+ let mut b = ~10 ;
271
+ b. clone_from ( & a) ;
272
+ assert_eq ! ( * b, 5 ) ;
273
+ }
274
+
275
+ #[ test]
276
+ fn test_deep_clone_from ( ) {
277
+ let a = ~5 ;
278
+ let mut b = ~10 ;
279
+ b. deep_clone_from ( & a) ;
280
+ assert_eq ! ( * b, 5 ) ;
281
+ }
282
+
237
283
#[ test]
238
284
fn test_extern_fn_clone ( ) {
239
285
trait Empty { }
0 commit comments