about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorkennytm <kennytm@gmail.com>2018-07-14 02:56:40 +0800
committerGitHub <noreply@github.com>2018-07-14 02:56:40 +0800
commita2c3713ea66a28f3546bb20fdd49686ee4ccc205 (patch)
tree656619a587e51f93bd4743f8ed018995fade92f6 /src
parentd8b84027848772fb99d4abf0450781cfd0d0b786 (diff)
parentc8f0e6f210caccdaea7dc59fd970c81018ddfb00 (diff)
downloadrust-a2c3713ea66a28f3546bb20fdd49686ee4ccc205.tar.gz
rust-a2c3713ea66a28f3546bb20fdd49686ee4ccc205.zip
Rollup merge of #52003 - Kerollmops:option-replace, r=Kimundi
Implement `Option::replace` in the core library

Here is the implementation of the `Option::replace` method. The first step of [the tracking issue #51998](https://github.com/rust-lang/rust/issues/51998).
Diffstat (limited to 'src')
-rw-r--r--src/libcore/option.rs27
-rw-r--r--src/libcore/tests/lib.rs1
-rw-r--r--src/libcore/tests/option.rs15
3 files changed, 43 insertions, 0 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index 20bc173f7e1..f3e823670aa 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -845,6 +845,33 @@ impl<T> Option<T> {
     pub fn take(&mut self) -> Option<T> {
         mem::replace(self, None)
     }
+
+    /// Replaces the actual value in the option by the value given in parameter,
+    /// returning the old value if present,
+    /// leaving a [`Some`] in its place without deinitializing either one.
+    ///
+    /// [`Some`]: #variant.Some
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(option_replace)]
+    ///
+    /// let mut x = Some(2);
+    /// let old = x.replace(5);
+    /// assert_eq!(x, Some(5));
+    /// assert_eq!(old, Some(2));
+    ///
+    /// let mut x = None;
+    /// let old = x.replace(3);
+    /// assert_eq!(x, Some(3));
+    /// assert_eq!(old, None);
+    /// ```
+    #[inline]
+    #[unstable(feature = "option_replace", issue = "51998")]
+    pub fn replace(&mut self, value: T) -> Option<T> {
+        mem::replace(self, Some(value))
+    }
 }
 
 impl<'a, T: Clone> Option<&'a T> {
diff --git a/src/libcore/tests/lib.rs b/src/libcore/tests/lib.rs
index 9d4a5213992..ca7db6e4639 100644
--- a/src/libcore/tests/lib.rs
+++ b/src/libcore/tests/lib.rs
@@ -44,6 +44,7 @@
 #![feature(reverse_bits)]
 #![feature(iterator_find_map)]
 #![feature(slice_internals)]
+#![feature(option_replace)]
 
 extern crate core;
 extern crate test;
diff --git a/src/libcore/tests/option.rs b/src/libcore/tests/option.rs
index 22109e28edd..bc3e61a4f54 100644
--- a/src/libcore/tests/option.rs
+++ b/src/libcore/tests/option.rs
@@ -297,3 +297,18 @@ fn test_try() {
     }
     assert_eq!(try_option_err(), Err(NoneError));
 }
+
+#[test]
+fn test_replace() {
+    let mut x = Some(2);
+    let old = x.replace(5);
+
+    assert_eq!(x, Some(5));
+    assert_eq!(old, Some(2));
+
+    let mut x = None;
+    let old = x.replace(3);
+
+    assert_eq!(x, Some(3));
+    assert_eq!(old, None);
+}