ownable_core/
as_clone.rs

1use crate::as_impl::impl_as;
2use crate::traits::{IntoOwned, ToBorrowed, ToOwned};
3use alloc::string::String;
4use core::borrow::{Borrow, BorrowMut};
5use core::cmp::Ordering;
6use core::fmt::{Debug, Display, Formatter};
7use core::hash::{Hash, Hasher};
8use core::ops::{Deref, DerefMut};
9
10/// Transparent wrapper for [`Clone`]able types to support all traits (by cloning).
11///
12/// ```rust
13/// # use ownable_core::{AsClone, IntoOwned};
14/// #[derive(Clone)]
15/// struct NotIntoOwned;
16///
17/// fn requires_into_owned<O: IntoOwned>(o: O) {
18///   // do stuff
19/// }
20///
21/// // `AsClone<NotIntoOwned>` implements `IntoOwned` through `Clone`
22/// requires_into_owned(AsClone(NotIntoOwned));
23/// ```
24///
25/// All trait impls work on the inner value as if there is no layer in between
26/// (e.g. `Display` does not add a `AsClone` to the output).
27#[repr(transparent)]
28pub struct AsClone<T: Clone>(pub T);
29
30impl<T: Clone> ToBorrowed<'_> for AsClone<T> {
31    #[inline(always)]
32    fn to_borrowed(&self) -> Self {
33        AsClone(self.0.clone())
34    }
35}
36
37impl<T: Clone> ToOwned for AsClone<T> {
38    type Owned = AsClone<T>;
39
40    #[inline(always)]
41    fn to_owned(&self) -> Self::Owned {
42        AsClone(self.0.clone())
43    }
44}
45
46impl<T: Clone> IntoOwned for AsClone<T> {
47    type Owned = AsClone<T>;
48
49    #[inline(always)]
50    fn into_owned(self) -> Self::Owned {
51        AsClone(self.0)
52    }
53}
54
55impl_as!(AsClone, Clone);
56
57// Clone specific
58
59impl From<&str> for AsClone<String> {
60    #[inline]
61    fn from(value: &str) -> Self {
62        AsClone(value.into())
63    }
64}