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
//! Tooling to check the correctness of `Drop` implementations. //! //! Properly testing a container type like `Vec<T>` requires verifying that every value in the //! container is neither leaked, nor dropped multiple times. //! //! To detect leaks, this crate provides a `DropToken` type whose drop implementation sets a flag in a //! `DropState` with interior mutability (specifically atomics). Secondly, these states are stored //! in a `DropCheck` set. If any any token hasn't been dropped when the `DropCheck` is dropped, the //! `DropCheck`'s drop impl panics: //! //! ```should_panic //! # use dropcheck::DropCheck; //! let dropcheck = DropCheck::new(); //! let token = dropcheck.token(); //! //! std::mem::forget(token); // leaked! //! // panics when dropcheck goes out of scope //! ``` //! //! Secondly, dropping a token twice panics: //! //! ```should_panic //! # use dropcheck::DropCheck; //! let dropcheck = DropCheck::new(); //! let mut token = dropcheck.token(); //! //! unsafe { //! std::ptr::drop_in_place(&mut token); //! std::ptr::drop_in_place(&mut token); // panics //! } //! ``` use std::fmt; use std::sync::{Arc, Weak, RwLock, atomic::{AtomicUsize, Ordering}}; /// A drop-checking token. /// /// Created by `DropCheck`. #[derive(Debug)] pub struct DropToken { set: Weak<RwLock<Vec<Arc<DropState>>>>, state: Arc<DropState>, } impl Drop for DropToken { fn drop(&mut self) { self.state.set_dropped(); } } /// Cloning a `DropToken` creates a fresh state, that's still tied to the `DropCheck` set that /// created the token. This means that leaking the cloned token is detected: /// /// ```should_panic /// # use dropcheck::DropCheck; /// let dropcheck = DropCheck::new(); /// let token = dropcheck.token(); /// /// let cloned_token = token.clone(); /// std::mem::forget(cloned_token); /// // panics when dropcheck is dropped /// ``` /// /// Since the new token is part of the set it came from, it affects `none_dropped`/`all_dropped`: /// /// ``` /// # use dropcheck::DropCheck; /// let dropcheck = DropCheck::new(); /// let token = dropcheck.token(); /// /// let cloned_token = token.clone(); /// assert!(dropcheck.none_dropped()); /// /// drop(cloned_token); /// assert!(!dropcheck.none_dropped()); /// ``` impl Clone for DropToken { fn clone(&self) -> Self { let state = DropState::new(); if let Some(set) = self.set.upgrade() { set.write().unwrap().push(Arc::clone(&state)); Self { set: Arc::downgrade(&set), state, } } else { Self { set: Weak::new(), state, } } } } /// The state of a particular `DropToken`. pub struct DropState { count: AtomicUsize, } impl fmt::Debug for DropState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct(&format!("DropState<{:p}>", self)) .field("count", &self.count) .finish() } } impl Drop for DropState { fn drop(&mut self) { match self.count.get_mut() { 1 => {}, 0 => panic!("token not dropped"), _ => panic!("invalid drop count: {}"), } } } impl DropState { /// Returns true if the token associated with this state has been dropped. pub fn is_dropped(&self) -> bool { !self.is_not_dropped() } /// The inverse of `is_dropped()`. pub fn is_not_dropped(&self) -> bool { match self.count.load(Ordering::SeqCst) { 0 => true, 1 => false, x => panic!("invalid drop count: {}", x), } } fn new() -> Arc<Self> { Arc::new(Self { count: AtomicUsize::new(0) }) } fn set_dropped(&self) { match self.count.swap(1, Ordering::SeqCst) { 0 => {}, 1 => panic!("already dropped"), x => panic!("invalid drop count: {}", x), } } } /// A set of `DropToken`'s. #[derive(Debug, Default)] pub struct DropCheck { set: Arc<RwLock<Vec<Arc<DropState>>>>, } impl Drop for DropCheck { fn drop(&mut self) { assert!(self.all_dropped(), "not all tokens dropped"); } } impl DropCheck { /// Creates a new `DropCheck` set. pub fn new() -> Self { Self::default() } fn push(&self, state: Arc<DropState>) { self.set.write().unwrap().push(state) } /// Creates a new `DropToken`, whose state is part of this set. pub fn token(&self) -> DropToken { let state = DropState::new(); self.push(Arc::clone(&state)); DropToken { set: Arc::downgrade(&self.set), state, } } /// Creates a new `DropToken`, and also gives you a handle to the state. /// /// # Examples /// /// Checking when an operation drops a value: /// /// ``` /// # use dropcheck::DropCheck; /// let dropcheck = DropCheck::new(); /// /// let mut v = vec![dropcheck.token(); 10]; /// /// let (t1, s1) = dropcheck.pair(); /// v.push(t1); /// /// assert!(s1.is_not_dropped()); /// v.pop(); /// assert!(s1.is_dropped()); // vec drops items immediately /// ``` pub fn pair(&self) -> (DropToken, Arc<DropState>) { let state = DropState::new(); self.push(Arc::clone(&state)); (DropToken { set: Arc::downgrade(&self.set), state: Arc::clone(&state), }, state) } /// Returns true if none of the `Token`s in this set have been dropped. /// /// # Examples /// /// ``` /// # use dropcheck::DropCheck; /// let set = DropCheck::new(); /// assert!(set.none_dropped()); // an empty set has no dropped tokens /// /// let t1 = set.token(); /// assert!(set.none_dropped()); /// /// let t2 = set.token(); /// assert!(set.none_dropped()); /// /// drop(t1); /// assert!(!set.none_dropped()); /// ``` pub fn none_dropped(&self) -> bool { self.set.read().unwrap() .iter().all(|state| state.is_not_dropped()) } /// Returns true if all of the `Token`s have been dropped. /// /// # Examples /// /// ``` /// # use dropcheck::DropCheck; /// let set = DropCheck::new(); /// assert!(set.all_dropped()); // all of the tokens in an empty set have been dropped /// /// let mut v = vec![]; /// for _ in 0 .. 100 { /// v.push(set.token()); /// } /// assert!(!set.all_dropped()); /// /// drop(v); /// assert!(set.all_dropped()); // vec has dropped every token in it /// ``` pub fn all_dropped(&self) -> bool { self.set.read().unwrap() .iter().all(|state| state.is_dropped()) } }