Skip to content

Commit b57de80

Browse files
authored
Implement TryClone for Arc<T>, Option<T>, and Result<T, E> (#12615)
1 parent bbfcd58 commit b57de80

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

crates/core/src/alloc/try_clone.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use crate::error::OutOfMemory;
22
use core::mem;
3+
use std_alloc::sync::Arc;
34

45
/// A trait for values that can be cloned, but contain owned, heap-allocated
56
/// values whose allocations may fail during cloning.
@@ -39,6 +40,40 @@ where
3940
}
4041
}
4142

43+
impl<T, E> TryClone for Result<T, E>
44+
where
45+
T: TryClone,
46+
E: TryClone,
47+
{
48+
#[inline]
49+
fn try_clone(&self) -> Result<Self, OutOfMemory> {
50+
match self {
51+
Ok(x) => Ok(Ok(x.try_clone()?)),
52+
Err(e) => Ok(Err(e.try_clone()?)),
53+
}
54+
}
55+
}
56+
57+
impl<T> TryClone for Option<T>
58+
where
59+
T: TryClone,
60+
{
61+
#[inline]
62+
fn try_clone(&self) -> Result<Self, OutOfMemory> {
63+
match self {
64+
Some(x) => Ok(Some(x.try_clone()?)),
65+
None => Ok(None),
66+
}
67+
}
68+
}
69+
70+
impl<T> TryClone for Arc<T> {
71+
#[inline]
72+
fn try_clone(&self) -> Result<Self, OutOfMemory> {
73+
Ok(self.clone())
74+
}
75+
}
76+
4277
macro_rules! impl_try_clone_via_clone {
4378
( $( $ty:ty ),* $(,)? ) => {
4479
$(

0 commit comments

Comments
 (0)