]> git.proxmox.com Git - rustc.git/blob - src/libcore/clone.rs
Imported Upstream version 1.6.0+dfsg1
[rustc.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` method.
21
22 #![stable(feature = "rust1", since = "1.0.0")]
23
24 use marker::Sized;
25
26 /// A common trait for cloning an object.
27 ///
28 /// This trait can be used with `#[derive]`.
29 #[stable(feature = "rust1", since = "1.0.0")]
30 pub trait Clone : Sized {
31 /// Returns a copy of the value.
32 ///
33 /// # Examples
34 ///
35 /// ```
36 /// let hello = "Hello"; // &str implements Clone
37 ///
38 /// assert_eq!("Hello", hello.clone());
39 /// ```
40 #[stable(feature = "rust1", since = "1.0.0")]
41 fn clone(&self) -> Self;
42
43 /// Performs copy-assignment from `source`.
44 ///
45 /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality,
46 /// but can be overridden to reuse the resources of `a` to avoid unnecessary
47 /// allocations.
48 #[inline(always)]
49 #[stable(feature = "rust1", since = "1.0.0")]
50 fn clone_from(&mut self, source: &Self) {
51 *self = source.clone()
52 }
53 }
54
55 #[stable(feature = "rust1", since = "1.0.0")]
56 impl<'a, T: ?Sized> Clone for &'a T {
57 /// Returns a shallow copy of the reference.
58 #[inline]
59 fn clone(&self) -> &'a T { *self }
60 }
61
62 macro_rules! clone_impl {
63 ($t:ty) => {
64 #[stable(feature = "rust1", since = "1.0.0")]
65 impl Clone for $t {
66 /// Returns a deep copy of the value.
67 #[inline]
68 fn clone(&self) -> $t { *self }
69 }
70 }
71 }
72
73 clone_impl! { isize }
74 clone_impl! { i8 }
75 clone_impl! { i16 }
76 clone_impl! { i32 }
77 clone_impl! { i64 }
78
79 clone_impl! { usize }
80 clone_impl! { u8 }
81 clone_impl! { u16 }
82 clone_impl! { u32 }
83 clone_impl! { u64 }
84
85 clone_impl! { f32 }
86 clone_impl! { f64 }
87
88 clone_impl! { () }
89 clone_impl! { bool }
90 clone_impl! { char }