Skip to content

Commit 1785f15

Browse files
authored
Rollup merge of #96222 - jmaargh:john-mark/clarify-from-raw-parts-docs, r=JohnTitor
Clarify docs for `from_raw_parts` on `Vec` and `String` Closes #95427 Original safety explanation for `from_raw_parts` was unclear on safety for consuming a C string. This clarifies when doing so is safe.
2 parents ddfc65d + 4dda047 commit 1785f15

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

library/alloc/src/string.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -770,7 +770,10 @@ impl String {
770770
/// * The first `length` bytes at `buf` need to be valid UTF-8.
771771
///
772772
/// Violating these may cause problems like corrupting the allocator's
773-
/// internal data structures.
773+
/// internal data structures. For example, it is normally **not** safe to
774+
/// build a `String` from a pointer to a C `char` array containing UTF-8
775+
/// _unless_ you are certain that array was originally allocated by the
776+
/// Rust standard library's allocator.
774777
///
775778
/// The ownership of `buf` is effectively transferred to the
776779
/// `String` which may then deallocate, reallocate or change the

library/alloc/src/vec/mod.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -489,8 +489,10 @@ impl<T> Vec<T> {
489489
/// * `length` needs to be less than or equal to `capacity`.
490490
///
491491
/// Violating these may cause problems like corrupting the allocator's
492-
/// internal data structures. For example it is **not** safe
493-
/// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
492+
/// internal data structures. For example it is normally **not** safe
493+
/// to build a `Vec<u8>` from a pointer to a C `char` array with length
494+
/// `size_t`, doing so is only safe if the array was initially allocated by
495+
/// a `Vec` or `String`.
494496
/// It's also not safe to build one from a `Vec<u16>` and its length, because
495497
/// the allocator cares about the alignment, and these two types have different
496498
/// alignments. The buffer was allocated with alignment 2 (for `u16`), but after

0 commit comments

Comments
 (0)