Skip to content

Add doc examples to str::from_utf8_unchecked_mut #44477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 15, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,34 @@ pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
/// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
///
/// [fromutf8]: fn.from_utf8_unchecked.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::str;
///
/// let mut heart = vec![240, 159, 146, 150];
/// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
///
/// assert_eq!("💖", heart);
/// ```
///
/// Invalid UTF-8:
///
/// ```
/// use std::str;
///
/// // Invalid bytes.
/// let mut bytes = vec![240, 40, 140, 188];
///
/// // Returns a str:
/// unsafe { str::from_utf8_unchecked_mut(&mut bytes) };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it turns out that constructing an invalid string in an 'unchecked' manner is considered "undefined behavior" and not something we want to add in here. although it might not be obvious for such a simple example as this, this sort of behavior can cause the program to become unpredictable and problematic. unfortunately, i think we might just need to remove this "Invalid UTF-8" section for this example

///
/// // from_utf8 returns an error instead:
/// assert!(str::from_utf8(&bytes).is_err());
/// ```
#[inline]
#[stable(feature = "str_mut_extras", since = "1.20.0")]
pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
Expand Down