Skip to content

Commit 18ef0de

Browse files
committed
Add doc examples to str::from_utf8_unchecked_mut
Fixes #44461
1 parent d290dec commit 18ef0de

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/libcore/str/mod.rs

+28
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,34 @@ pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
382382
/// See the immutable version, [`from_utf8_unchecked()`][fromutf8], for more information.
383383
///
384384
/// [fromutf8]: fn.from_utf8_unchecked.html
385+
///
386+
/// # Examples
387+
///
388+
/// Basic usage:
389+
///
390+
/// ```
391+
/// use std::str;
392+
///
393+
/// let mut heart = vec![240, 159, 146, 150];
394+
/// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
395+
///
396+
/// assert_eq!("💖", heart);
397+
/// ```
398+
///
399+
/// Invalid UTF-8:
400+
///
401+
/// ```
402+
/// use std::str;
403+
///
404+
/// // Invalid bytes.
405+
/// let mut bytes = vec![240, 40, 140, 188];
406+
///
407+
/// // Returns a str:
408+
/// unsafe { str::from_utf8_unchecked_mut(&mut bytes) };
409+
///
410+
/// // from_utf8 returns an error instead:
411+
/// assert!(str::from_utf8(&bytes).is_err());
412+
/// ```
385413
#[inline]
386414
#[stable(feature = "str_mut_extras", since = "1.20.0")]
387415
pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {

0 commit comments

Comments
 (0)