]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/converts.rs
Rollup merge of #104865 - pratushrai0309:bootstrap, r=jyn514
[rust.git] / library / core / src / str / converts.rs
1 //! Ways to create a `str` from bytes slice.
2
3 use crate::mem;
4
5 use super::validations::run_utf8_validation;
6 use super::Utf8Error;
7
8 /// Converts a slice of bytes to a string slice.
9 ///
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.
15 ///
16 /// [`&str`]: str
17 /// [byteslice]: slice
18 ///
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.
23 ///
24 /// If you need a `String` instead of a `&str`, consider
25 /// [`String::from_utf8`][string].
26 ///
27 /// [string]: ../../std/string/struct.String.html#method.from_utf8
28 ///
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.
33 ///
34 /// [byteslice]: slice
35 ///
36 /// # Errors
37 ///
38 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
39 /// provided slice is not UTF-8.
40 ///
41 /// # Examples
42 ///
43 /// Basic usage:
44 ///
45 /// ```
46 /// use std::str;
47 ///
48 /// // some bytes, in a vector
49 /// let sparkle_heart = vec![240, 159, 146, 150];
50 ///
51 /// // We know these bytes are valid, so just use `unwrap()`.
52 /// let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap();
53 ///
54 /// assert_eq!("💖", sparkle_heart);
55 /// ```
56 ///
57 /// Incorrect bytes:
58 ///
59 /// ```
60 /// use std::str;
61 ///
62 /// // some invalid bytes, in a vector
63 /// let sparkle_heart = vec![0, 159, 146, 150];
64 ///
65 /// assert!(str::from_utf8(&sparkle_heart).is_err());
66 /// ```
67 ///
68 /// See the docs for [`Utf8Error`] for more details on the kinds of
69 /// errors that can be returned.
70 ///
71 /// A "stack allocated string":
72 ///
73 /// ```
74 /// use std::str;
75 ///
76 /// // some bytes, in a stack-allocated array
77 /// let sparkle_heart = [240, 159, 146, 150];
78 ///
79 /// // We know these bytes are valid, so just use `unwrap()`.
80 /// let sparkle_heart: &str = str::from_utf8(&sparkle_heart).unwrap();
81 ///
82 /// assert_eq!("💖", sparkle_heart);
83 /// ```
84 #[stable(feature = "rust1", since = "1.0.0")]
85 #[rustc_const_stable(feature = "const_str_from_utf8_shared", since = "1.63.0")]
86 #[rustc_allow_const_fn_unstable(str_internals)]
87 pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
88     // FIXME: This should use `?` again, once it's `const`
89     match run_utf8_validation(v) {
90         Ok(_) => {
91             // SAFETY: validation succeeded.
92             Ok(unsafe { from_utf8_unchecked(v) })
93         }
94         Err(err) => Err(err),
95     }
96 }
97
98 /// Converts a mutable slice of bytes to a mutable string slice.
99 ///
100 /// # Examples
101 ///
102 /// Basic usage:
103 ///
104 /// ```
105 /// use std::str;
106 ///
107 /// // "Hello, Rust!" as a mutable vector
108 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
109 ///
110 /// // As we know these bytes are valid, we can use `unwrap()`
111 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
112 ///
113 /// assert_eq!("Hello, Rust!", outstr);
114 /// ```
115 ///
116 /// Incorrect bytes:
117 ///
118 /// ```
119 /// use std::str;
120 ///
121 /// // Some invalid bytes in a mutable vector
122 /// let mut invalid = vec![128, 223];
123 ///
124 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
125 /// ```
126 /// See the docs for [`Utf8Error`] for more details on the kinds of
127 /// errors that can be returned.
128 #[stable(feature = "str_mut_extras", since = "1.20.0")]
129 #[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
130 pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
131     // This should use `?` again, once it's `const`
132     match run_utf8_validation(v) {
133         Ok(_) => {
134             // SAFETY: validation succeeded.
135             Ok(unsafe { from_utf8_unchecked_mut(v) })
136         }
137         Err(err) => Err(err),
138     }
139 }
140
141 /// Converts a slice of bytes to a string slice without checking
142 /// that the string contains valid UTF-8.
143 ///
144 /// See the safe version, [`from_utf8`], for more information.
145 ///
146 /// # Safety
147 ///
148 /// The bytes passed in must be valid UTF-8.
149 ///
150 /// # Examples
151 ///
152 /// Basic usage:
153 ///
154 /// ```
155 /// use std::str;
156 ///
157 /// // some bytes, in a vector
158 /// let sparkle_heart = vec![240, 159, 146, 150];
159 ///
160 /// let sparkle_heart = unsafe {
161 ///     str::from_utf8_unchecked(&sparkle_heart)
162 /// };
163 ///
164 /// assert_eq!("💖", sparkle_heart);
165 /// ```
166 #[inline]
167 #[must_use]
168 #[stable(feature = "rust1", since = "1.0.0")]
169 #[rustc_const_stable(feature = "const_str_from_utf8_unchecked", since = "1.55.0")]
170 pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
171     // SAFETY: the caller must guarantee that the bytes `v` are valid UTF-8.
172     // Also relies on `&str` and `&[u8]` having the same layout.
173     unsafe { mem::transmute(v) }
174 }
175
176 /// Converts a slice of bytes to a string slice without checking
177 /// that the string contains valid UTF-8; mutable version.
178 ///
179 /// See the immutable version, [`from_utf8_unchecked()`] for more information.
180 ///
181 /// # Examples
182 ///
183 /// Basic usage:
184 ///
185 /// ```
186 /// use std::str;
187 ///
188 /// let mut heart = vec![240, 159, 146, 150];
189 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
190 ///
191 /// assert_eq!("💖", heart);
192 /// ```
193 #[inline]
194 #[must_use]
195 #[stable(feature = "str_mut_extras", since = "1.20.0")]
196 #[rustc_const_unstable(feature = "const_str_from_utf8_unchecked_mut", issue = "91005")]
197 pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
198     // SAFETY: the caller must guarantee that the bytes `v`
199     // are valid UTF-8, thus the cast to `*mut str` is safe.
200     // Also, the pointer dereference is safe because that pointer
201     // comes from a reference which is guaranteed to be valid for writes.
202     unsafe { &mut *(v as *mut [u8] as *mut str) }
203 }