about summary refs log tree commit diff
path: root/src/liballoc/vec.rs
diff options
context:
space:
mode:
authorJake Goulding <jake.goulding@gmail.com>2019-10-22 12:48:52 -0400
committerJake Goulding <jake.goulding@gmail.com>2019-10-25 11:25:52 -0400
commit6600cf604091a99bba990d41b93885b40c02a97d (patch)
tree53532045ef05b19d5dd34f08575ee645329ae6ab /src/liballoc/vec.rs
parentdce8fabc62ed393152c53c65c492c8f3ae324eda (diff)
downloadrust-6600cf604091a99bba990d41b93885b40c02a97d.tar.gz
rust-6600cf604091a99bba990d41b93885b40c02a97d.zip
Add {String,Vec}::into_raw_parts
Diffstat (limited to 'src/liballoc/vec.rs')
-rw-r--r--src/liballoc/vec.rs39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs
index c8fb8971234..641f9eafa8d 100644
--- a/src/liballoc/vec.rs
+++ b/src/liballoc/vec.rs
@@ -358,6 +358,44 @@ impl<T> Vec<T> {
         }
     }
 
+    /// Decomposes a `Vec<T>` into its raw components.
+    ///
+    /// Returns the raw pointer to the underlying data, the length of
+    /// the vector (in elements), and the allocated capacity of the
+    /// data (in elements). These are the same arguments in the same
+    /// order as the arguments to [`from_raw_parts`].
+    ///
+    /// After calling this function, the caller is responsible for the
+    /// memory previously managed by the `Vec`. The only way to do
+    /// this is to convert the raw pointer, length, and capacity back
+    /// into a `Vec` with the [`from_raw_parts`] function, allowing
+    /// the destructor to perform the cleanup.
+    ///
+    /// [`from_raw_parts`]: #method.from_raw_parts
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(vec_into_raw_parts)]
+    /// let v: Vec<i32> = vec![-1, 0, 1];
+    ///
+    /// let (ptr, len, cap) = v.into_raw_parts();
+    ///
+    /// let rebuilt = unsafe {
+    ///     // We can now make changes to the components, such as
+    ///     // transmuting the raw pointer to a compatible type.
+    ///     let ptr = ptr as *mut u32;
+    ///
+    ///     Vec::from_raw_parts(ptr, len, cap)
+    /// };
+    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
+    /// ```
+    #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
+    pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
+        let mut me = mem::ManuallyDrop::new(self);
+        (me.as_mut_ptr(), me.len(), me.capacity())
+    }
+
     /// Creates a `Vec<T>` directly from the raw components of another vector.
     ///
     /// # Safety
@@ -391,6 +429,7 @@ impl<T> Vec<T> {
     ///
     /// let v = vec![1, 2, 3];
     ///
+    // FIXME Update this when vec_into_raw_parts is stabilized
     /// // Prevent running `v`'s destructor so we are in complete control
     /// // of the allocation.
     /// let mut v = mem::ManuallyDrop::new(v);