]> git.lizzy.rs Git - rust.git/commitdiff
Clarify docs for from_raw_parts
authorjmaargh <jmaargh@gmail.com>
Tue, 19 Apr 2022 20:12:55 +0000 (21:12 +0100)
committerjmaargh <jmaargh@gmail.com>
Tue, 19 Apr 2022 20:12:55 +0000 (21:12 +0100)
Original safety explanation for from_raw_parts was
unclear on safety for consuming a C string. This
clarifies when doing so is safe.

library/alloc/src/string.rs
library/alloc/src/vec/mod.rs

index e97c1637fd5a26fea0b4674e7e7de6419d363ac5..2272c5b7330dc872b0386646fecb655288061c1b 100644 (file)
@@ -770,7 +770,10 @@ pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
     /// * The first `length` bytes at `buf` need to be valid UTF-8.
     ///
     /// Violating these may cause problems like corrupting the allocator's
-    /// internal data structures.
+    /// internal data structures. For example, it is normally **not** safe to
+    /// build a `String` from a pointer to a C `char` array containing UTF-8
+    /// _unless_ you are certain that array was originally allocated by the
+    /// Rust standard library's allocator.
     ///
     /// The ownership of `buf` is effectively transferred to the
     /// `String` which may then deallocate, reallocate or change the
index 8c2f52172ee70d44286fdadb06d0b982694eae33..9bf42e779c9983f2f728ed6f7a914e4602084db4 100644 (file)
@@ -489,8 +489,10 @@ pub fn with_capacity(capacity: usize) -> Self {
     /// * `length` needs to be less than or equal to `capacity`.
     ///
     /// Violating these may cause problems like corrupting the allocator's
-    /// internal data structures. For example it is **not** safe
-    /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
+    /// internal data structures. For example it is normally **not** safe
+    /// to build a `Vec<u8>` from a pointer to a C `char` array with length
+    /// `size_t`, doing so is only safe if the array was initially allocated by
+    /// a `Vec` or `String`.
     /// It's also not safe to build one from a `Vec<u16>` and its length, because
     /// the allocator cares about the alignment, and these two types have different
     /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after