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 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
#![doc(html_root_url = "https://docs.rs/high_mem_utils/0.1.1/")] #![feature(vec_leak, untagged_unions)] /*! This crate provides high-level memory abstractions used for ensure memory and exception safety in some patterns. High-level signifies that it only brings safe abstractions for some cases of transmute and others unsafe functions in the mem or ptr module,does not provide a custom allocator or garbage collector neither depends on the [core::alloc] unstable lib. At the moment this crate is nightly only,this will change if the features [`vec_leak`] and [`untagged_unions`] get stabilished. # Examples ``` use high_mem_utils::{CatchStr, DontDrop, DropBy}; let mut string = String::from("Hello world!"); let catch = CatchStr::new(string.clone()); assert_eq!(catch.leaked().to_string(), string); // leaked returns &&mut str,not use to_string // is a bit difficult cast rigth now assert_eq!(catch.seal(), string); // catch consumed let mut a = [1, 2, 3]; { let elem = DropBy::new([2, 3, 4], |e| { a = e.clone(); }); assert_eq!(*elem, [2, 3, 4]); } assert_eq!(a, [2, 3, 4]); unsafe { let b = DontDrop([1, 2, 3]); // we're not dropping here because we will have two variables // pointing to the same memory and "b" lives for shorter a = [0; 3]; b.as_ptr().copy_to(a.as_mut_ptr(), 3); } assert_eq!(a, [1, 2, 3]); ``` [`vec_leak`]: https://github.com/rust-lang/rust/issues/62195 [`untagged_unions`]: https://github.com/rust-lang/rust/issues/32836 [core::alloc]: https://doc.rust-lang.org/core/alloc/index.html */ use std::mem::{self, ManuallyDrop}; use std::ops::{Deref, DerefMut}; /// An union type that can be leaked or sealed(owned),useful when you want to give temporal global access to a particular value. pub union Catch<'a, T> { leaked: &'a mut T, sealed: ManuallyDrop<Box<T>>, } impl<'a, T> Catch<'a, T> { /// Creates a new Catch with a leak, you can lately get the underlying value and consume the Catch /// with the [`seal`](#method.seal) method. pub fn new(a: Box<T>) -> Self { Catch { leaked: Box::leak(a), } } /// Returns a a reference to the leaked field,'cause the only ways for construct this union returns /// a leaked one,for warranty never transmute stack to heap data,this method does not use transmute /// implicitly. pub fn leaked(&self) -> &&'a mut T { unsafe { &self.leaked } } /// Consumes the Catch and gets the inner Box\<T\>,preventing the memory leak. /// /// This does a call to transmute but,as the only ways to construct this union gives you a leaked one /// this never trigger undefined behavior by itself. pub fn seal(self) -> Box<T> { unsafe { ManuallyDrop::into_inner(self.sealed) } } /// Consumes the Catch and returns a mutable reference pointing to leaked data. pub fn leak(self) -> &'a mut T { unsafe { self.leaked } } /// Creates a new Catch from a mutable reference to T,without checking if T is in the heap. /// /// # Safety /// /// This function should only be used with data returned by leak from a safely construct Catch or with /// data returned by Box::leak otherwise will trigger undefined behavior if seal is called. pub unsafe fn from_leaked(leaked: &'a mut T) -> Self { Catch { leaked } } } /// An union slice that can be leaked or sealed(owned),useful when you want to give temporal global access /// to a particular sequence. pub union CatchSeq<'a, T> { leaked: &'a mut [T], sealed: ManuallyDrop<Box<[T]>>, } impl<'a, T> CatchSeq<'a, T> { /// Creates a new CatchSeq with a leak, you can lately get the underlying sequence and consume the CatchSeq /// with the [`seal`](#method.seal) method. pub fn new(a: Vec<T>) -> Self { CatchSeq { leaked: Vec::leak(a), } } /// Returns a a reference to the leaked field,as the only safe ways for construct this union returns a leaked /// one,for warranty never transmute stack to heap data,this method does not use transmute implicitly. pub fn leaked(&self) -> &&'a mut [T] { unsafe { &self.leaked } } /// Consumes the Catch and gets the inner Vec<T>, preventing the memory leak. /// /// This does a call to transmute but,as the only safe ways for construct this union returns a leaked /// one,this never trigger undefined behavior by itself. pub fn seal(self) -> Vec<T> { unsafe { ManuallyDrop::into_inner(self.sealed).into_vec() } } /// Consumes the CatchSeq and returns a mutable reference pointing to leaked data. pub fn leak(self) -> &'a mut [T] { unsafe { self.leaked } } /// Creates a new CatchSeq from a `&mut [T]`,without checking if the referent is in the heap. /// /// # Safety /// /// This function should only be used with data returned by leak from a safely constructed CatchSeq or /// with data returned by Vec::leak otherwise this will trigger undefined behavior if[`seal`](#method.seal) /// is called. pub unsafe fn from_leaked(leaked: &'a mut [T]) -> Self { CatchSeq { leaked } } } /// An union string that can be leaked or sealed(owned),useful when you want to give temporal global access /// to a particular string. pub union CatchStr<'a> { leaked: &'a mut str, sealed: ManuallyDrop<Box<str>>, } impl<'a> CatchStr<'a> { /// Creates a new CatchStr with a leak, you can lately get the underlying string and consume the CatchStr /// with the [`seal`](#method.seal) method. pub fn new(a: String) -> Self { CatchStr { leaked: Box::leak(a.into_boxed_str()), } } /// Returns a a reference to the leaked field,as the only safe ways for construct this union returns a leaked /// one,for warranty never transmute stack to heap data,this method does not use transmute implicitly. pub fn leaked(&self) -> &&'a mut str { unsafe { &self.leaked } } /// Consumes the Catch and gets the inner String, preventing the memory leak. /// /// This does a call to transmute but,as the only safe ways for construct this union return a leaked /// one,this never trigger undefined behavior by itself. pub fn seal(self) -> String { unsafe { ManuallyDrop::into_inner(self.sealed).into_string() } } /// Consumes the CatchStr and returns a mutable reference pointing to leaked data. pub fn leak(self) -> &'a mut str { unsafe { self.leaked } } /// Creates a new CatchStr from a `&mut str`,without checking if the referent is in the heap. /// /// # Safety /// /// This function should only be used with data returned by leak from a safely constructed CatchStr or /// with data returned by `Box::leak(s.into_boxed_str())` otherwise this will trigger undefined behavior /// if [`seal`](#method.seal) is called. pub unsafe fn from_leaked(leaked: &'a mut str) -> Self { CatchStr { leaked } } } /// A wrapper for an implementation of drop that [`mem::take`] the value and [`mem::forget`]s it. /// /// This might be useful if you want assuring that a particular destructor not run if it can lead to /// a double-free or another memory issue. /// /// This type is particularly not recomended for reference types because as such they can never be null /// and the value is still dropped. Neither on types with a costly initialization because it replaces the /// forgotten value with the `Default` one,these values should not implement it anyways. /// /// This type has the same implications that forget except for the fact that this ensures that the value /// is never dropped even on panic,unless you abort.In general [`DontDropOpt`](./struct.DontDropOpt.html) is preferred. /// /// It derefs to T. /// /// [`mem::take`]: https://doc.rust-lang.org/core/mem/fn.take.html pub struct DontDrop<T: Default>(pub T); impl<T: Default> Drop for DontDrop<T> { fn drop(&mut self) { mem::forget(mem::take(&mut self.0)); } } impl<T: Default> Deref for DontDrop<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } impl<T: Default> DerefMut for DontDrop<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } /// A wrapper for an implementation of drop that [`mem::forget`] the previous value and replace it with None. /// /// This might be useful if you want assuring that a particular destructor not run if it can lead to /// a double-free or another memory issue. /// /// This type is particularly not recomended for reference types because as such they can never be null /// and the value is still dropped. /// /// This type has the same implications that [`mem::forget`] except for the fact that this ensures that the /// value is never dropped even on panic,unless you abort. /// /// It derefs to Option<T>. pub struct DontDropOpt<T>(Option<T>); impl<T> DontDropOpt<T> { /// Construct a new `DontDropOpt` from a value,this has no effect if the value is a reference. pub fn new(a: T) -> Self { DontDropOpt(Some(a)) } } impl<T> Drop for DontDropOpt<T> { fn drop(&mut self) { mem::forget(&mut self.0.take()); } } impl<T> Deref for DontDropOpt<T> { type Target = Option<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> DerefMut for DontDropOpt<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } /// A wrapper that calls the given closure at Drop. Useful when you have a conditional assign of one /// that,once assigned,you want to warranty a call to it with the given T,and then drop it. /// /// It derefs to T. pub struct DropBy<T, F: FnMut(&mut T)> { pub value: T, pub clos: F } impl<T, F: FnMut(&mut T)> DropBy<T, F> { pub fn new(value: T, clos: F) -> Self { DropBy {value, clos} } } impl<T, F: FnMut(&mut T)> Drop for DropBy<T, F> { fn drop(&mut self) { (self.clos)(&mut self.value) } } impl<T, F: FnMut(&mut T)> Deref for DropBy<T, F> { type Target = T; fn deref(&self) -> &Self::Target { &self.value } } impl<T, F: FnMut(&mut T)> DerefMut for DropBy<T, F> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.value } }