]> git.lizzy.rs Git - rust.git/commitdiff
Add `get_mut` methods to the `RefCell` and `Cell`
authorTobias Bucher <tobiasbucher5991@gmail.com>
Thu, 5 May 2016 22:39:25 +0000 (00:39 +0200)
committerTobias Bucher <tobiasbucher5991@gmail.com>
Thu, 5 May 2016 22:40:51 +0000 (00:40 +0200)
This is safe since the borrow checker ensures that we have the only
mutable reference to the struct, thus we can safely borrow its interior.

Tracking issue is #33444.

src/libcore/cell.rs

index 257027dad5ed26f14cc9a03a9983e4f1527c661c..19c778b023490282790d9b6993de94a00cc0828f 100644 (file)
@@ -232,6 +232,18 @@ pub fn set(&self, value: T) {
     pub fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
         &self.value
     }
+
+    /// Returns a mutable reference to the underlying data.
+    ///
+    /// This call borrows `Cell` mutably (at compile-time) which guarantees
+    /// that we possess the only reference.
+    #[inline]
+    #[unstable(feature = "cell_get_mut", issue = "33444")]
+    pub fn get_mut(&mut self) -> &mut T {
+        unsafe {
+            &mut *self.value.get()
+        }
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -455,6 +467,18 @@ pub fn borrow_mut(&self) -> RefMut<T> {
     pub unsafe fn as_unsafe_cell(&self) -> &UnsafeCell<T> {
         &self.value
     }
+
+    /// Returns a mutable reference to the underlying data.
+    ///
+    /// This call borrows `RefCell` mutably (at compile-time) so there is no
+    /// need for dynamic checks.
+    #[inline]
+    #[unstable(feature = "cell_get_mut", issue="33444")]
+    pub fn get_mut(&mut self) -> &mut T {
+        unsafe {
+            &mut *self.value.get()
+        }
+    }
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]