]> git.lizzy.rs Git - rust.git/blob - src/libcore/clone.rs
Auto merge of #43648 - RalfJung:jemalloc-debug, r=alexcrichton
[rust.git] / src / libcore / clone.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! The `Clone` trait for types that cannot be 'implicitly copied'.
12 //!
13 //! In Rust, some simple types are "implicitly copyable" and when you
14 //! assign them or pass them as arguments, the receiver will get a copy,
15 //! leaving the original value in place. These types do not require
16 //! allocation to copy and do not have finalizers (i.e. they do not
17 //! contain owned boxes or implement [`Drop`]), so the compiler considers
18 //! them cheap and safe to copy. For other types copies must be made
19 //! explicitly, by convention implementing the [`Clone`] trait and calling
20 //! the [`clone`][clone] method.
21 //!
22 //! [`Clone`]: trait.Clone.html
23 //! [clone]: trait.Clone.html#tymethod.clone
24 //! [`Drop`]: ../../std/ops/trait.Drop.html
25 //!
26 //! Basic usage example:
27 //!
28 //! ```
29 //! let s = String::new(); // String type implements Clone
30 //! let copy = s.clone(); // so we can clone it
31 //! ```
32 //!
33 //! To easily implement the Clone trait, you can also use
34 //! `#[derive(Clone)]`. Example:
35 //!
36 //! ```
37 //! #[derive(Clone)] // we add the Clone trait to Morpheus struct
38 //! struct Morpheus {
39 //!    blue_pill: f32,
40 //!    red_pill: i64,
41 //! }
42 //!
43 //! fn main() {
44 //!    let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
45 //!    let copy = f.clone(); // and now we can clone it!
46 //! }
47 //! ```
48
49 #![stable(feature = "rust1", since = "1.0.0")]
50
51 /// A common trait for the ability to explicitly duplicate an object.
52 ///
53 /// Differs from [`Copy`] in that [`Copy`] is implicit and extremely inexpensive, while
54 /// `Clone` is always explicit and may or may not be expensive. In order to enforce
55 /// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
56 /// may reimplement `Clone` and run arbitrary code.
57 ///
58 /// Since `Clone` is more general than [`Copy`], you can automatically make anything
59 /// [`Copy`] be `Clone` as well.
60 ///
61 /// ## Derivable
62 ///
63 /// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
64 /// implementation of [`clone`] calls [`clone`] on each field.
65 ///
66 /// ## How can I implement `Clone`?
67 ///
68 /// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
69 /// if `T: Copy`, `x: T`, and `y: &T`, then `let x = y.clone();` is equivalent to `let x = *y;`.
70 /// Manual implementations should be careful to uphold this invariant; however, unsafe code
71 /// must not rely on it to ensure memory safety.
72 ///
73 /// An example is an array holding more than 32 elements of a type that is `Clone`; the standard
74 /// library only implements `Clone` up until arrays of size 32. In this case, the implementation of
75 /// `Clone` cannot be `derive`d, but can be implemented as:
76 ///
77 /// [`Copy`]: ../../std/marker/trait.Copy.html
78 /// [`clone`]: trait.Clone.html#tymethod.clone
79 ///
80 /// ```
81 /// #[derive(Copy)]
82 /// struct Stats {
83 ///    frequencies: [i32; 100],
84 /// }
85 ///
86 /// impl Clone for Stats {
87 ///     fn clone(&self) -> Stats { *self }
88 /// }
89 /// ```
90 #[stable(feature = "rust1", since = "1.0.0")]
91 #[cfg_attr(not(stage0), lang = "clone")]
92 pub trait Clone : Sized {
93     /// Returns a copy of the value.
94     ///
95     /// # Examples
96     ///
97     /// ```
98     /// let hello = "Hello"; // &str implements Clone
99     ///
100     /// assert_eq!("Hello", hello.clone());
101     /// ```
102     #[stable(feature = "rust1", since = "1.0.0")]
103     fn clone(&self) -> Self;
104
105     /// Performs copy-assignment from `source`.
106     ///
107     /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
108     /// but can be overridden to reuse the resources of `a` to avoid unnecessary
109     /// allocations.
110     #[inline]
111     #[stable(feature = "rust1", since = "1.0.0")]
112     fn clone_from(&mut self, source: &Self) {
113         *self = source.clone()
114     }
115 }
116
117 // FIXME(aburka): these structs are used solely by #[derive] to
118 // assert that every component of a type implements Clone or Copy.
119 //
120 // These structs should never appear in user code.
121 #[doc(hidden)]
122 #[allow(missing_debug_implementations)]
123 #[unstable(feature = "derive_clone_copy",
124            reason = "deriving hack, should not be public",
125            issue = "0")]
126 pub struct AssertParamIsClone<T: Clone + ?Sized> { _field: ::marker::PhantomData<T> }
127 #[doc(hidden)]
128 #[allow(missing_debug_implementations)]
129 #[unstable(feature = "derive_clone_copy",
130            reason = "deriving hack, should not be public",
131            issue = "0")]
132 pub struct AssertParamIsCopy<T: Copy + ?Sized> { _field: ::marker::PhantomData<T> }
133
134 #[stable(feature = "rust1", since = "1.0.0")]
135 #[cfg(stage0)]
136 impl<'a, T: ?Sized> Clone for &'a T {
137     /// Returns a shallow copy of the reference.
138     #[inline]
139     fn clone(&self) -> &'a T { *self }
140 }
141
142 macro_rules! clone_impl {
143     ($t:ty) => {
144         #[stable(feature = "rust1", since = "1.0.0")]
145         #[cfg(stage0)]
146         impl Clone for $t {
147             /// Returns a deep copy of the value.
148             #[inline]
149             fn clone(&self) -> $t { *self }
150         }
151     }
152 }
153
154 clone_impl! { isize }
155 clone_impl! { i8 }
156 clone_impl! { i16 }
157 clone_impl! { i32 }
158 clone_impl! { i64 }
159 clone_impl! { i128 }
160
161 clone_impl! { usize }
162 clone_impl! { u8 }
163 clone_impl! { u16 }
164 clone_impl! { u32 }
165 clone_impl! { u64 }
166 clone_impl! { u128 }
167
168 clone_impl! { f32 }
169 clone_impl! { f64 }
170
171 clone_impl! { ! }
172 clone_impl! { () }
173 clone_impl! { bool }
174 clone_impl! { char }