1 //! Ways to create a `str` from bytes slice.
5 use super::validations::run_utf8_validation;
8 /// Converts a slice of bytes to a string slice.
10 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
11 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
12 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
13 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
14 /// UTF-8, and then does the conversion.
17 /// [byteslice]: ../../std/primitive.slice.html
19 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
20 /// incur the overhead of the validity check, there is an unsafe version of
21 /// this function, [`from_utf8_unchecked`], which has the same
22 /// behavior but skips the check.
24 /// If you need a `String` instead of a `&str`, consider
25 /// [`String::from_utf8`][string].
27 /// [string]: ../../std/string/struct.String.html#method.from_utf8
29 /// Because you can stack-allocate a `[u8; N]`, and you can take a
30 /// [`&[u8]`][byteslice] of it, this function is one way to have a
31 /// stack-allocated string. There is an example of this in the
32 /// examples section below.
34 /// [byteslice]: ../../std/primitive.slice.html
38 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
39 /// provided slice is not UTF-8.
48 /// // some bytes, in a vector
49 /// let sparkle_heart = vec![240, 159, 146, 150];
51 /// // We know these bytes are valid, so just use `unwrap()`.
52 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
54 /// assert_eq!("💖", sparkle_heart);
62 /// // some invalid bytes, in a vector
63 /// let sparkle_heart = vec![0, 159, 146, 150];
65 /// assert!(str::from_utf8(&sparkle_heart).is_err());
68 /// See the docs for [`Utf8Error`] for more details on the kinds of
69 /// errors that can be returned.
71 /// A "stack allocated string":
76 /// // some bytes, in a stack-allocated array
77 /// let sparkle_heart = [240, 159, 146, 150];
79 /// // We know these bytes are valid, so just use `unwrap()`.
80 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
82 /// assert_eq!("💖", sparkle_heart);
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
86 run_utf8_validation(v)?;
87 // SAFETY: Just ran validation.
88 Ok(unsafe { from_utf8_unchecked(v) })
91 /// Converts a mutable slice of bytes to a mutable string slice.
100 /// // "Hello, Rust!" as a mutable vector
101 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
103 /// // As we know these bytes are valid, we can use `unwrap()`
104 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
106 /// assert_eq!("Hello, Rust!", outstr);
114 /// // Some invalid bytes in a mutable vector
115 /// let mut invalid = vec![128, 223];
117 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
119 /// See the docs for [`Utf8Error`] for more details on the kinds of
120 /// errors that can be returned.
121 #[stable(feature = "str_mut_extras", since = "1.20.0")]
122 pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
123 run_utf8_validation(v)?;
124 // SAFETY: Just ran validation.
125 Ok(unsafe { from_utf8_unchecked_mut(v) })
128 /// Converts a slice of bytes to a string slice without checking
129 /// that the string contains valid UTF-8.
131 /// See the safe version, [`from_utf8`], for more information.
135 /// This function is unsafe because it does not check that the bytes passed to
136 /// it are valid UTF-8. If this constraint is violated, undefined behavior
137 /// results, as the rest of Rust assumes that [`&str`]s are valid UTF-8.
148 /// // some bytes, in a vector
149 /// let sparkle_heart = vec![240, 159, 146, 150];
151 /// let sparkle_heart = unsafe {
152 /// str::from_utf8_unchecked(&sparkle_heart)
155 /// assert_eq!("💖", sparkle_heart);
158 #[stable(feature = "rust1", since = "1.0.0")]
159 #[rustc_const_unstable(feature = "const_str_from_utf8_unchecked", issue = "75196")]
160 #[rustc_allow_const_fn_unstable(const_fn_transmute)]
161 pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
162 // SAFETY: the caller must guarantee that the bytes `v` are valid UTF-8.
163 // Also relies on `&str` and `&[u8]` having the same layout.
164 unsafe { mem::transmute(v) }
167 /// Converts a slice of bytes to a string slice without checking
168 /// that the string contains valid UTF-8; mutable version.
170 /// See the immutable version, [`from_utf8_unchecked()`] for more information.
179 /// let mut heart = vec![240, 159, 146, 150];
180 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
182 /// assert_eq!("💖", heart);
185 #[stable(feature = "str_mut_extras", since = "1.20.0")]
186 pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
187 // SAFETY: the caller must guarantee that the bytes `v`
188 // are valid UTF-8, thus the cast to `*mut str` is safe.
189 // Also, the pointer dereference is safe because that pointer
190 // comes from a reference which is guaranteed to be valid for writes.
191 unsafe { &mut *(v as *mut [u8] as *mut str) }