From 71714edf8b8a0e710f4a17a120b86e07e279ccc7 Mon Sep 17 00:00:00 2001 From: David Spies Date: Fri, 2 Apr 2021 08:34:43 -0700 Subject: [PATCH 1/2] Add drop_leak and drop_leak_mut --- library/core/src/cell.rs | 46 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 9a2908c275da8..68e839d1435e6 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1034,6 +1034,52 @@ impl RefCell { self.get_mut() } + /// Assert that a single leaked immutable guard has been cleaned up. + /// + /// # Examples + /// + /// ``` + /// #![feature(cell_leak)] + /// use std::cell::{RefCell, Ref}; + /// + /// let mut c = RefCell::new(0); + /// Ref::leak(c.borrow()); + /// + /// assert!(c.try_borrow_mut().is_err()); + /// c.drop_leak(); + /// assert!(c.try_borrow_mut().is_ok()); + /// ``` + #[unstable(feature = "cell_leak", issue = "69099")] + pub unsafe fn drop_leak(&self) { + self.borrow.update(|x| { + assert!(x > 0, "Cell not borrowed immutably"); + x - 1 + }); + } + + /// Assert that a single leaked mutable guard has been cleaned up. + /// + /// # Examples + /// + /// ``` + /// #![feature(cell_leak)] + /// use std::cell::{RefCell, RefMut}; + /// + /// let mut c = RefCell::new(0); + /// RefMut::leak(c.borrow_mut()); + /// + /// assert!(c.try_borrow().is_err()); + /// c.drop_leak_mut(); + /// assert!(c.try_borrow().is_ok()); + /// ``` + #[unstable(feature = "cell_leak", issue = "69099")] + pub unsafe fn drop_leak_mut(&self) { + self.borrow.update(|x| { + assert!(x < 0, "Cell not borrowed mutably"); + x + 1 + }); + } + /// Immutably borrows the wrapped value, returning an error if the value is /// currently mutably borrowed. /// From 2572f3b535101ed0bd1247b09a6658c48327413c Mon Sep 17 00:00:00 2001 From: David Spies Date: Fri, 2 Apr 2021 09:07:33 -0700 Subject: [PATCH 2/2] Forgot the unsafe block in the doctest --- library/core/src/cell.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 68e839d1435e6..4ef41e974d5ec 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1046,7 +1046,7 @@ impl RefCell { /// Ref::leak(c.borrow()); /// /// assert!(c.try_borrow_mut().is_err()); - /// c.drop_leak(); + /// unsafe { c.drop_leak() }; /// assert!(c.try_borrow_mut().is_ok()); /// ``` #[unstable(feature = "cell_leak", issue = "69099")] @@ -1069,7 +1069,7 @@ impl RefCell { /// RefMut::leak(c.borrow_mut()); /// /// assert!(c.try_borrow().is_err()); - /// c.drop_leak_mut(); + /// unsafe { c.drop_leak_mut() }; /// assert!(c.try_borrow().is_ok()); /// ``` #[unstable(feature = "cell_leak", issue = "69099")]