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
use std::convert::TryFrom; pub trait ClonedFrom<T: ?Sized>: Sized { fn cloned_from(value: &T) -> Self; } pub trait ToCloned<T: ?Sized>: Sized { fn to_cloned(&self) -> T; } pub trait TryClonedFrom<T: ?Sized>: Sized { type Error; fn try_cloned_from(value: &T) -> Result<Self, Self::Error>; } pub trait TryToCloned<T>: Sized { type Error; fn try_to_cloned(&self) -> Result<T, Self::Error>; } impl<T, U> ClonedFrom<T> for U where T: Clone + ?Sized, U: From<T>, { fn cloned_from(value: &T) -> Self { U::from(value.clone()) } } impl<T, U> ToCloned<U> for T where U: ClonedFrom<T>, { fn to_cloned(&self) -> U { U::cloned_from(self) } } impl<T, U> TryClonedFrom<T> for U where T: Clone + ?Sized, U: TryFrom<T>, { type Error = <U as TryFrom<T>>::Error; fn try_cloned_from(value: &T) -> Result<U, Self::Error> { <Self as TryFrom<T>>::try_from(value.clone()) } } impl<T, U> TryToCloned<U> for T where U: TryClonedFrom<T>, { type Error = U::Error; fn try_to_cloned(&self) -> Result<U, Self::Error> { U::try_cloned_from(self) } } #[cfg(test)] mod test { use super::*; #[derive(Clone)] struct ItemA { a: u64, b: String, } #[allow(dead_code)] struct ItemA2 { a: u64, b: String, } #[allow(dead_code)] struct ItemB { a: ItemA, b: bool, } impl ClonedFrom<ItemA> for ItemA2 { fn cloned_from(value: &ItemA) -> Self { Self { a: value.a, b: value.b.clone(), } } } impl TryClonedFrom<ItemA> for ItemB { type Error = (); fn try_cloned_from(value: &ItemA) -> Result<Self, Self::Error> { Ok(Self { a: value.clone(), b: true, }) } } #[test] fn cloned_from() { let _item_a2 = ItemA2::cloned_from(&ItemA { a: 24, b: "lol".into(), }); } #[test] fn cloned_from_self() { let _item_a = ItemA::cloned_from(&ItemA { a: 24, b: "lol".into(), }); } #[test] fn to_cloned() { let item_a = ItemA { a: 24, b: "lol".into(), }; let _item_a2: ItemA2 = item_a.to_cloned(); } #[test] fn to_cloned_self() { let item_a = ItemA { a: 24, b: "lol".into(), }; let _item_a: ItemA = item_a.to_cloned(); } #[test] fn try_to_cloned() { let item_a = ItemA { a: 24, b: "lol".into(), }; let _item_b: Result<ItemB, _> = item_a.try_to_cloned(); } #[test] fn try_cloned_from() { let item_a = ItemA { a: 24, b: "lol".into(), }; let _item_b = ItemB::try_cloned_from(&item_a); } }