Path: blob/main/crates/core/src/alloc/try_clone.rs
3075 views
use crate::error::OutOfMemory;1use core::mem;23/// A trait for values that can be cloned, but contain owned, heap-allocated4/// values whose allocations may fail during cloning.5pub trait TryClone: Sized {6/// Attempt to clone `self`, returning an error if any allocation fails7/// during cloning.8fn try_clone(&self) -> Result<Self, OutOfMemory>;9}1011impl<T> TryClone for *mut T12where13T: ?Sized,14{15#[inline]16fn try_clone(&self) -> Result<Self, OutOfMemory> {17Ok(*self)18}19}2021impl<T> TryClone for core::ptr::NonNull<T>22where23T: ?Sized,24{25#[inline]26fn try_clone(&self) -> Result<Self, OutOfMemory> {27Ok(*self)28}29}3031impl<'a, T> TryClone for &'a T32where33T: ?Sized,34{35#[inline]36fn try_clone(&self) -> Result<Self, OutOfMemory> {37Ok(*self)38}39}4041macro_rules! impl_try_clone_via_clone {42( $( $ty:ty ),* $(,)? ) => {43$(44impl TryClone for $ty {45#[inline]46fn try_clone(&self) -> Result<Self, OutOfMemory> {47Ok(self.clone())48}49}50)*51};52}5354impl_try_clone_via_clone! {55bool, char,56u8, u16, u32, u64, u128, usize,57i8, i16, i32, i64, i128, isize,58f32, f64,59}6061macro_rules! tuples {62( $( $( $t:ident ),* );*) => {63$(64impl<$($t),*> TryClone for ( $($t,)* )65where66$( $t: TryClone ),*67{68#[inline]69fn try_clone(&self) -> Result<Self, OutOfMemory> {70#[allow(non_snake_case, reason = "macro code")]71let ( $($t,)* ) = self;72Ok(( $( $t.try_clone()?, )* ))73}74}75)*76};77}7879tuples! {80A;81A, B;82A, B, C;83A, B, C, D;84A, B, C, D, E;85A, B, C, D, E, F;86A, B, C, D, E, F, G;87A, B, C, D, E, F, G, H;88A, B, C, D, E, F, G, H, I;89A, B, C, D, E, F, G, H, I, J;90}9192impl<T> TryClone for mem::ManuallyDrop<T>93where94T: TryClone,95{96fn try_clone(&self) -> Result<Self, OutOfMemory> {97Ok(mem::ManuallyDrop::new((**self).try_clone()?))98}99}100101#[cfg(feature = "std")]102impl_try_clone_via_clone! {103std::hash::RandomState104}105106#[cfg(not(feature = "std"))]107impl_try_clone_via_clone! {108hashbrown::DefaultHashBuilder109}110111112