1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//! The `TryClone` trait for types that cannot be 'implicitly copied'.
//!
//! In Rust, some simple types are "implicitly copyable" and when you assign
//! them or pass them as arguments, the receiver will get a copy, leaving the
//! original value in place. These types do not require allocation to copy and
//! do not have finalizers (i.e., they do not contain owned boxes or implement
//! [`Drop`]), so the compiler considers them cheap and safe to copy. For other
//! types copies must be made explicitly, by convention implementing the
//! [`TryClone`] trait and calling the [`try_clone`] method.
//!
//! [`try_clone`]: TryClone::try_clone
//!
//! Basic usage example:
//!
//! ```
//! use rune::alloc::String;
//! use rune::alloc::prelude::*;
//!
//! // String type implements TryClone
//! let s = String::new();
//! // ... so we can clone it
//! let copy = s.try_clone()?;
//! # Ok::<_, rune::alloc::Error>(())
//! ```
//!
//! To easily implement the TryClone trait, you can also use
//! `#[derive(TryClone)]`. Example:
//!
//! ```
//! use rune::alloc::prelude::*;
//!
//! // we add the TryClone trait to Morpheus struct
//! #[derive(TryClone)]
//! struct Morpheus {
//!    blue_pill: f32,
//!    red_pill: i64,
//! }
//!
//! let f = Morpheus { blue_pill: 0.0, red_pill: 0 };
//! // and now we can clone it!
//! let copy = f.try_clone()?;
//! # Ok::<_, rune::alloc::Error>(())
//! ```

use crate::error::Error;

#[doc(inline)]
pub use rune_alloc_macros::TryClone;

/// Fallible `TryClone` trait.
pub trait TryClone: Sized {
    /// Try to clone the current value, raising an allocation error if it's unsuccessful.
    fn try_clone(&self) -> Result<Self, Error>;

    /// Performs copy-assignment from `source`.
    ///
    /// `a.try_clone_from(&b)` is equivalent to `a = b.clone()` in
    /// functionality, but can be overridden to reuse the resources of `a` to
    /// avoid unnecessary allocations.
    #[inline]
    fn try_clone_from(&mut self, source: &Self) -> Result<(), Error> {
        *self = source.try_clone()?;
        Ok(())
    }
}

/// Marker trait for types which are `Copy`.
#[cfg_attr(rune_nightly, rustc_specialization_trait)]
pub trait TryCopy: TryClone {}

impl<T: ?Sized> TryClone for &T {
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(*self)
    }
}

macro_rules! impl_tuple {
    ($count:expr $(, $ty:ident $var:ident $num:expr)*) => {
        impl<$($ty,)*> TryClone for ($($ty,)*) where $($ty: TryClone,)* {
            #[inline]
            fn try_clone(&self) -> Result<Self, Error> {
                let ($($var,)*) = self;
                Ok(($($var.try_clone()?,)*))
            }
        }
    }
}

repeat_macro!(impl_tuple);

macro_rules! impl_copy {
    ($ty:ty) => {
        impl TryClone for $ty {
            #[inline]
            fn try_clone(&self) -> Result<Self, Error> {
                Ok(*self)
            }
        }

        impl TryCopy for $ty {}
    };
}

impl_copy!(char);
impl_copy!(bool);
impl_copy!(usize);
impl_copy!(isize);
impl_copy!(u8);
impl_copy!(u16);
impl_copy!(u32);
impl_copy!(u64);
impl_copy!(u128);
impl_copy!(i8);
impl_copy!(i16);
impl_copy!(i32);
impl_copy!(i64);
impl_copy!(i128);
impl_copy!(f32);
impl_copy!(f64);

impl_copy!(::core::num::NonZeroUsize);
impl_copy!(::core::num::NonZeroIsize);
impl_copy!(::core::num::NonZeroU8);
impl_copy!(::core::num::NonZeroU16);
impl_copy!(::core::num::NonZeroU32);
impl_copy!(::core::num::NonZeroU64);
impl_copy!(::core::num::NonZeroU128);
impl_copy!(::core::num::NonZeroI8);
impl_copy!(::core::num::NonZeroI16);
impl_copy!(::core::num::NonZeroI32);
impl_copy!(::core::num::NonZeroI64);
impl_copy!(::core::num::NonZeroI128);

impl<T, E> TryClone for ::core::result::Result<T, E>
where
    T: TryClone,
    E: TryClone,
{
    #[inline]
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(match self {
            Ok(value) => Ok(value.try_clone()?),
            Err(value) => Err(value.try_clone()?),
        })
    }
}

impl<T> TryClone for ::core::option::Option<T>
where
    T: TryClone,
{
    #[inline]
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(match self {
            Some(value) => Some(value.try_clone()?),
            None => None,
        })
    }
}

#[cfg(feature = "alloc")]
impl<T: ?Sized> TryClone for ::rust_alloc::sync::Arc<T> {
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(self.clone())
    }
}

#[cfg(feature = "alloc")]
impl<T: ?Sized> TryClone for ::rust_alloc::rc::Rc<T> {
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(self.clone())
    }
}

#[cfg(feature = "alloc")]
impl<T> TryClone for ::rust_alloc::boxed::Box<T>
where
    T: TryClone,
{
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(::rust_alloc::boxed::Box::new(self.as_ref().try_clone()?))
    }
}

#[cfg(feature = "alloc")]
impl<T> TryClone for ::rust_alloc::boxed::Box<[T]>
where
    T: TryClone,
{
    fn try_clone(&self) -> Result<Self, Error> {
        // TODO: use a fallible box allocation.
        let mut out = ::rust_alloc::vec::Vec::with_capacity(self.len());

        for value in self.iter() {
            out.push(value.try_clone()?);
        }

        Ok(out.into())
    }
}

#[cfg(feature = "alloc")]
impl TryClone for ::rust_alloc::string::String {
    #[inline]
    fn try_clone(&self) -> Result<Self, Error> {
        // TODO: use fallible allocations for component.
        Ok(self.clone())
    }
}

#[cfg(all(test, feature = "alloc"))]
impl<T> TryClone for ::rust_alloc::vec::Vec<T>
where
    T: TryClone,
{
    #[inline]
    fn try_clone(&self) -> Result<Self, Error> {
        let mut out = ::rust_alloc::vec::Vec::with_capacity(self.len());

        for value in self {
            out.push(value.try_clone()?);
        }

        Ok(out)
    }
}

impl TryClone for crate::path::PathBuf {
    fn try_clone(&self) -> Result<Self, Error> {
        Ok(self.clone())
    }
}