]> git.proxmox.com Git - rustc.git/blame - src/libcore/clone.rs
New upstream version 1.14.0+dfsg1
[rustc.git] / src / libcore / clone.rs
CommitLineData
1a4d82fc
JJ
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
54a0048b 11//! The `Clone` trait for types that cannot be 'implicitly copied'.
1a4d82fc
JJ
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
9e0c209e 17//! contain owned boxes or implement [`Drop`]), so the compiler considers
1a4d82fc 18//! them cheap and safe to copy. For other types copies must be made
9e0c209e
SL
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
54a0048b
SL
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//! ```
1a4d82fc 48
85aaf69f 49#![stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 50
3157f602 51/// A common trait for the ability to explicitly duplicate an object.
92a42be0 52///
9e0c209e 53/// Differs from [`Copy`] in that [`Copy`] is implicit and extremely inexpensive, while
3157f602 54/// `Clone` is always explicit and may or may not be expensive. In order to enforce
9e0c209e 55/// these characteristics, Rust does not allow you to reimplement [`Copy`], but you
3157f602
XL
56/// may reimplement `Clone` and run arbitrary code.
57///
9e0c209e
SL
58/// Since `Clone` is more general than [`Copy`], you can automatically make anything
59/// [`Copy`] be `Clone` as well.
3157f602
XL
60///
61/// ## Derivable
62///
63/// This trait can be used with `#[derive]` if all fields are `Clone`. The `derive`d
9e0c209e 64/// implementation of [`clone()`] calls [`clone()`] on each field.
3157f602
XL
65///
66/// ## How can I implement `Clone`?
a7813a04 67///
9e0c209e 68/// Types that are [`Copy`] should have a trivial implementation of `Clone`. More formally:
a7813a04
XL
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.
3157f602
XL
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///
9e0c209e
SL
77/// [`Copy`]: ../../std/marker/trait.Copy.html
78/// [`clone()`]: trait.Clone.html#tymethod.clone
79///
3157f602
XL
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/// ```
85aaf69f 90#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
91pub trait Clone : Sized {
92 /// Returns a copy of the value.
c34b1796
AL
93 ///
94 /// # Examples
95 ///
96 /// ```
97 /// let hello = "Hello"; // &str implements Clone
98 ///
99 /// assert_eq!("Hello", hello.clone());
100 /// ```
85aaf69f 101 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
102 fn clone(&self) -> Self;
103
9346a6ac 104 /// Performs copy-assignment from `source`.
1a4d82fc
JJ
105 ///
106 /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
107 /// but can be overridden to reuse the resources of `a` to avoid unnecessary
108 /// allocations.
109 #[inline(always)]
9346a6ac 110 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc
JJ
111 fn clone_from(&mut self, source: &Self) {
112 *self = source.clone()
113 }
114}
115
9e0c209e
SL
116// FIXME(aburka): these structs are used solely by #[derive] to
117// assert that every component of a type implements Clone or Copy.
a7813a04 118//
9e0c209e
SL
119// These structs should never appear in user code.
120#[doc(hidden)]
121#[allow(missing_debug_implementations)]
122#[unstable(feature = "derive_clone_copy",
123 reason = "deriving hack, should not be public",
124 issue = "0")]
125pub struct AssertParamIsClone<T: Clone + ?Sized> { _field: ::marker::PhantomData<T> }
126#[doc(hidden)]
127#[allow(missing_debug_implementations)]
128#[unstable(feature = "derive_clone_copy",
129 reason = "deriving hack, should not be public",
130 issue = "0")]
131pub struct AssertParamIsCopy<T: Copy + ?Sized> { _field: ::marker::PhantomData<T> }
a7813a04 132
85aaf69f 133#[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 134impl<'a, T: ?Sized> Clone for &'a T {
9346a6ac 135 /// Returns a shallow copy of the reference.
1a4d82fc
JJ
136 #[inline]
137 fn clone(&self) -> &'a T { *self }
138}
139
140macro_rules! clone_impl {
141 ($t:ty) => {
85aaf69f 142 #[stable(feature = "rust1", since = "1.0.0")]
1a4d82fc 143 impl Clone for $t {
9346a6ac 144 /// Returns a deep copy of the value.
1a4d82fc
JJ
145 #[inline]
146 fn clone(&self) -> $t { *self }
147 }
148 }
149}
150
85aaf69f 151clone_impl! { isize }
1a4d82fc
JJ
152clone_impl! { i8 }
153clone_impl! { i16 }
154clone_impl! { i32 }
155clone_impl! { i64 }
156
85aaf69f 157clone_impl! { usize }
1a4d82fc
JJ
158clone_impl! { u8 }
159clone_impl! { u16 }
160clone_impl! { u32 }
161clone_impl! { u64 }
162
163clone_impl! { f32 }
164clone_impl! { f64 }
165
166clone_impl! { () }
167clone_impl! { bool }
168clone_impl! { char }