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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
//! This crate only provides the `MaybeOwned` enum //! //! Take a look at it's documentation for more information. //! #![warn(missing_docs)] use std::convert::From; use std::clone::Clone; use std::ops::Deref; use std::default::Default; use self::MaybeOwned::*; /// This type provides a way to store data to which you either have a /// reference to or which you do own. /// /// It provides `From<T>`, `From<&'a T>` implementations and, in difference /// to `Cow` does _not_ require `ToOwned` to be implemented which makes it /// compatible with non cloneable data, as a draw back of this it does not /// know about `ToOwned`. As a consequence of it can't know that `&str` should /// be the borrowed version of `String` and not `&String` this is especially /// bad wrt. `Box` as the borrowed version of `Box<T>` would be `&Box<T>`. /// /// While this crate has some drawbacks compared to `Cow` is has the benefit, /// that it works with Types which neither implement `Clone` nor `ToOwned`. /// Another benefit lies in the ability to write API functions which accept /// a generic parameter `E: Into<MaybeOwned<'a, T>>` as the API consumer can /// pass `T`, `&'a T` and `MaybeOwned<'a, T>` as argument, without requiring /// a explicit `Cow::Onwed` or a split into two functions one accepting /// owed and the other borrowed values. /// /// # Alternatives /// /// If you mainly have values implementing `ToOwned` like `&str`/`String`, `Path`/`PathBuf` or /// `&[T]`/`Vec<T>` using `std::borrow::Cow` might be preferable. /// /// If you want to be able to treat `&T`, `&mut T`, `Box<T>` and `Arc<T>` the same /// consider using [`reffers::rbma::RBMA`](https://docs.rs/reffers) /// (through not all types/platforms are supported because /// as it relies on the fact that for many pointers the lowest two bits are 0, and stores /// the discriminant in them, nevertheless this is can only be used with 32bit-aligned data, /// e.g. using a &u8 _might_ fail). RBMA also allows you to recover a `&mut T` if it was created /// from `Box<T>`, `&mut T` or a unique `Arc`. /// /// /// # Examples /// /// ``` /// # use maybe_owned::MaybeOwned; /// struct PseudoBigData(u8); /// fn pseudo_register_fn<'a, E>(_val: E) where E: Into<MaybeOwned<'a, PseudoBigData>> { } /// /// let data = PseudoBigData(12); /// let data2 = PseudoBigData(13); /// /// pseudo_register_fn(&data); /// pseudo_register_fn(&data); /// pseudo_register_fn(data2); /// pseudo_register_fn(MaybeOwned::Owned(PseudoBigData(111))); /// ``` /// /// ``` /// # use maybe_owned::MaybeOwned; /// #[repr(C)] /// struct OpaqueFFI { /// ref1: * const u8 /// //we also might want to have PhantomData etc. /// } /// /// // does not work as it does not implement `ToOwned` /// // let _ = Cow::Owned(OpaqueFFI { ref1: 0 as *const u8}); /// /// // ok, MaybeOwned can do this (but can't do &str<->String as tread of) /// let _ = MaybeOwned::Owned(OpaqueFFI { ref1: 0 as *const u8 }); /// ``` #[derive(Debug)] pub enum MaybeOwned<'a, T: 'a> { /// owns T Owned(T), /// has a reference to T Borrowed(&'a T) } impl<'a, T> MaybeOwned<'a, T> { /// returns true if the data is owned else false pub fn is_owned(&self) -> bool { match *self { Owned(_) => true, Borrowed(_) => false } } } impl<'a, T> Deref for MaybeOwned<'a, T> { type Target = T; fn deref(&self) -> &T { match *self { Owned(ref v) => v, Borrowed(v) => v } } } impl<'a, T> From<&'a T> for MaybeOwned<'a, T> { fn from(v: &'a T) -> MaybeOwned<'a, T> { Borrowed(v) } } impl<'a, T> From<T> for MaybeOwned<'a, T> { fn from(v: T) -> MaybeOwned<'a, T> { Owned(v) } } impl<'a, T> Default for MaybeOwned<'a, T> where T: Default { fn default() -> Self { Owned(T::default()) } } impl<'a, T> Clone for MaybeOwned<'a, T> where T: Clone { fn clone(&self) -> MaybeOwned<'a, T> { match *self { Owned(ref v) => Owned(v.clone()), Borrowed(v) => Borrowed(v) } } } impl<'a, T> MaybeOwned<'a, T> where T: Clone { /// Aquires a mutable reference to owned data. /// /// Clones data if it is not already owned. /// /// ## Example /// /// ``` /// use maybe_owned::MaybeOwned; /// /// #[derive(Clone, Debug, PartialEq, Eq)] /// struct PseudoBigData(u8); /// /// let data = PseudoBigData(12); /// /// let mut maybe: MaybeOwned<PseudoBigData> = (&data).into(); /// assert_eq!(false, maybe.is_owned()); /// /// { /// let reference = maybe.to_mut(); /// assert_eq!(&mut PseudoBigData(12), reference); /// } /// assert!(maybe.is_owned()); /// ``` /// pub fn to_mut(&mut self) -> &mut T { match *self { Owned(ref mut v) => v, Borrowed(v) => { *self = Owned(v.clone()); match *self { Owned(ref mut v) => v, Borrowed(..) => unreachable!() } } } } /// Extracts the owned data. /// /// If the data is borrowed it is cloned before being extracted. pub fn into_owned(self) -> T { match self { Owned(v) => v, Borrowed(v) => v.clone() } } } #[cfg(test)] mod tests { use super::MaybeOwned; type TestType = Vec<()>; fn with_into<'a, I: Into<MaybeOwned<'a, TestType>>>(v: I) -> MaybeOwned<'a, TestType> { v.into() } #[test] fn is_owned() { let data = TestType::default(); assert!(MaybeOwned::Owned(data).is_owned()); } #[test] fn into_with_owned() { //ty check if it accepts references let data = TestType::default(); assert!(with_into(data).is_owned()) } #[test] fn into_with_borrow() { //ty check if it accepts references let data = TestType::default(); assert!(!with_into(&data).is_owned()); } #[test] fn clone_owned() { let maybe = MaybeOwned::<TestType>::default(); assert!(maybe.clone().is_owned()); } #[test] fn clone_borrow() { let data = TestType::default(); let maybe: MaybeOwned<TestType> = (&data).into(); assert!(!maybe.clone().is_owned()); } #[test] fn to_mut() { let data = TestType::default(); let mut maybe: MaybeOwned<TestType> = (&data).into(); assert!(!maybe.is_owned()); { let _mut_ref = maybe.to_mut(); } assert!(maybe.is_owned()); } #[test] fn into_inner() { let data = vec![1u32,2]; let maybe: MaybeOwned<Vec<u32>> = (&data).into(); assert_eq!(data, maybe.into_owned()); } #[test] fn has_default() { #[derive(Default)] struct TestType(u8); let _x: MaybeOwned<TestType> = Default::default(); } #[test] fn has_clone() { #[derive(Clone)] struct TestType(u8); let _x = TestType(12).clone(); } }