Skip to main content

core/str/
converts.rs

1//! Ways to create a `str` from bytes slice.
2
3use super::Utf8Error;
4use super::validations::run_utf8_validation;
5use crate::{mem, ptr};
6
7/// Converts a slice of bytes to a string slice.
8///
9/// This is an alias to [`str::from_utf8`].
10///
11/// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
12/// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
13/// the two. Not all byte slices are valid string slices, however: [`&str`] requires
14/// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
15/// UTF-8, and then does the conversion.
16///
17/// [`&str`]: str
18/// [byteslice]: slice
19///
20/// If you are sure that the byte slice is valid UTF-8, and you don't want to
21/// incur the overhead of the validity check, there is an unsafe version of
22/// this function, [`from_utf8_unchecked`], which has the same
23/// behavior but skips the check.
24///
25/// If you need a `String` instead of a `&str`, consider
26/// [`String::from_utf8`][string].
27///
28/// [string]: ../../std/string/struct.String.html#method.from_utf8
29///
30/// Because you can stack-allocate a `[u8; N]`, and you can take a
31/// [`&[u8]`][byteslice] of it, this function is one way to have a
32/// stack-allocated string. There is an example of this in the
33/// examples section below.
34///
35/// [byteslice]: slice
36///
37/// # Errors
38///
39/// Returns `Err` if the slice is not UTF-8 with a description as to why the
40/// provided slice is not UTF-8.
41///
42/// # Examples
43///
44/// Basic usage:
45///
46/// ```
47/// use std::str;
48///
49/// // some bytes, in a vector
50/// let sparkle_heart = vec![240, 159, 146, 150];
51///
52/// // We can use the ? (try) operator to check if the bytes are valid
53/// let sparkle_heart = str::from_utf8(&sparkle_heart)?;
54///
55/// assert_eq!("💖", sparkle_heart);
56/// # Ok::<_, str::Utf8Error>(())
57/// ```
58///
59/// Incorrect bytes:
60///
61/// ```
62/// use std::str;
63///
64/// // some invalid bytes, in a vector
65/// let sparkle_heart = vec![0, 159, 146, 150];
66///
67/// assert!(str::from_utf8(&sparkle_heart).is_err());
68/// ```
69///
70/// See the docs for [`Utf8Error`] for more details on the kinds of
71/// errors that can be returned.
72///
73/// A "stack allocated string":
74///
75/// ```
76/// use std::str;
77///
78/// // some bytes, in a stack-allocated array
79/// let sparkle_heart = [240, 159, 146, 150];
80///
81/// // We know these bytes are valid, so just use `unwrap()`.
82/// let sparkle_heart: &str = str::from_utf8(&sparkle_heart).unwrap();
83///
84/// assert_eq!("💖", sparkle_heart);
85/// ```
86#[stable(feature = "rust1", since = "1.0.0")]
87#[rustc_const_stable(feature = "const_str_from_utf8_shared", since = "1.63.0")]
88#[rustc_diagnostic_item = "str_from_utf8"]
89#[ferrocene::prevalidated]
90pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
91    // FIXME(const-hack): This should use `?` again, once it's `const`
92    match run_utf8_validation(v) {
93        Ok(_) => {
94            // SAFETY: validation succeeded.
95            Ok(unsafe { from_utf8_unchecked(v) })
96        }
97        Err(err) => Err(err),
98    }
99}
100
101/// Converts a mutable slice of bytes to a mutable string slice.
102///
103/// This is an alias to [`str::from_utf8_mut`].
104///
105/// # Examples
106///
107/// Basic usage:
108///
109/// ```
110/// use std::str;
111///
112/// // "Hello, Rust!" as a mutable vector
113/// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
114///
115/// // As we know these bytes are valid, we can use `unwrap()`
116/// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
117///
118/// assert_eq!("Hello, Rust!", outstr);
119/// ```
120///
121/// Incorrect bytes:
122///
123/// ```
124/// use std::str;
125///
126/// // Some invalid bytes in a mutable vector
127/// let mut invalid = vec![128, 223];
128///
129/// assert!(str::from_utf8_mut(&mut invalid).is_err());
130/// ```
131/// See the docs for [`Utf8Error`] for more details on the kinds of
132/// errors that can be returned.
133#[stable(feature = "str_mut_extras", since = "1.20.0")]
134#[rustc_const_stable(feature = "const_str_from_utf8", since = "1.87.0")]
135#[rustc_diagnostic_item = "str_from_utf8_mut"]
136#[ferrocene::prevalidated]
137pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
138    // FIXME(const-hack): This should use `?` again, once it's `const`
139    match run_utf8_validation(v) {
140        Ok(_) => {
141            // SAFETY: validation succeeded.
142            Ok(unsafe { from_utf8_unchecked_mut(v) })
143        }
144        Err(err) => Err(err),
145    }
146}
147
148/// Converts a slice of bytes to a string slice without checking
149/// that the string contains valid UTF-8.
150///
151/// This is an alias to [`str::from_utf8_unchecked`].
152///
153/// See the safe version, [`from_utf8`], for more information.
154///
155/// # Safety
156///
157/// The bytes passed in must be valid UTF-8.
158///
159/// # Examples
160///
161/// Basic usage:
162///
163/// ```
164/// use std::str;
165///
166/// // some bytes, in a vector
167/// let sparkle_heart = vec![240, 159, 146, 150];
168///
169/// let sparkle_heart = unsafe {
170///     str::from_utf8_unchecked(&sparkle_heart)
171/// };
172///
173/// assert_eq!("💖", sparkle_heart);
174/// ```
175#[inline]
176#[must_use]
177#[stable(feature = "rust1", since = "1.0.0")]
178#[rustc_const_stable(feature = "const_str_from_utf8_unchecked", since = "1.55.0")]
179#[rustc_diagnostic_item = "str_from_utf8_unchecked"]
180#[ferrocene::prevalidated]
181pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
182    // SAFETY: the caller must guarantee that the bytes `v` are valid UTF-8.
183    // Also relies on `&str` and `&[u8]` having the same layout.
184    unsafe { mem::transmute(v) }
185}
186
187/// Converts a slice of bytes to a string slice without checking
188/// that the string contains valid UTF-8; mutable version.
189///
190/// This is an alias to [`str::from_utf8_unchecked_mut`].
191///
192/// See the immutable version, [`from_utf8_unchecked()`] for documentation and safety requirements.
193///
194/// # Examples
195///
196/// Basic usage:
197///
198/// ```
199/// use std::str;
200///
201/// let mut heart = vec![240, 159, 146, 150];
202/// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
203///
204/// assert_eq!("💖", heart);
205/// ```
206#[inline]
207#[must_use]
208#[stable(feature = "str_mut_extras", since = "1.20.0")]
209#[rustc_const_stable(feature = "const_str_from_utf8_unchecked_mut", since = "1.83.0")]
210#[rustc_diagnostic_item = "str_from_utf8_unchecked_mut"]
211#[ferrocene::prevalidated]
212pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
213    // SAFETY: the caller must guarantee that the bytes `v`
214    // are valid UTF-8, thus the cast to `*mut str` is safe.
215    // Also, the pointer dereference is safe because that pointer
216    // comes from a reference which is guaranteed to be valid for writes.
217    unsafe { &mut *(v as *mut [u8] as *mut str) }
218}
219
220/// Creates a `&str` from a pointer and a length.
221///
222/// The pointed-to bytes must be valid UTF-8.
223/// If this might not be the case, use `str::from_utf8(slice::from_raw_parts(ptr, len))`,
224/// which will return an `Err` if the data isn't valid UTF-8.
225///
226/// This function is the `str` equivalent of [`slice::from_raw_parts`](crate::slice::from_raw_parts).
227/// See that function's documentation for safety concerns and examples.
228///
229/// The mutable version of this function is [`from_raw_parts_mut`].
230#[inline]
231#[must_use]
232#[unstable(feature = "str_from_raw_parts", issue = "119206")]
233#[ferrocene::prevalidated]
234pub const unsafe fn from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str {
235    // SAFETY: the caller must uphold the safety contract for `from_raw_parts`.
236    unsafe { &*ptr::from_raw_parts(ptr, len) }
237}
238
239/// Creates a `&mut str` from a pointer and a length.
240///
241/// The pointed-to bytes must be valid UTF-8.
242/// If this might not be the case, use `str::from_utf8_mut(slice::from_raw_parts_mut(ptr, len))`,
243/// which will return an `Err` if the data isn't valid UTF-8.
244///
245/// This function is the `str` equivalent of [`slice::from_raw_parts_mut`](crate::slice::from_raw_parts_mut).
246/// See that function's documentation for safety concerns and examples.
247///
248/// The immutable version of this function is [`from_raw_parts`].
249#[inline]
250#[must_use]
251#[unstable(feature = "str_from_raw_parts", issue = "119206")]
252#[ferrocene::prevalidated]
253pub const unsafe fn from_raw_parts_mut<'a>(ptr: *mut u8, len: usize) -> &'a mut str {
254    // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`.
255    unsafe { &mut *ptr::from_raw_parts_mut(ptr, len) }
256}