Skip to content

Commit 805e0f4

Browse files
authored
Unrolled build for rust-lang#136517
Rollup merge of rust-lang#136517 - m4rch3n1ng:inherent-str-constructors, r=jhpratt implement inherent str constructors implement rust-lang#131114 this implements - str::from_utf8 - str::from_utf8_mut - str::from_utf8_unchecked - str::from_utf8_unchecked_mut i left `std::str::from_raw_parts` and `std::str::from_raw_parts_mut` out of this as those are unstable and were not mentioned by the tracking issue or the original pull request, but i can add those here as well. i was also unsure of what to do with the `rustc_const_(un)stable` attributes: i removed the `#[rustc_const_stable]` attribute from `str::from_utf8`, `str::from_utf8_unchecked` and `str::from_utf8_unchecked_mut`, and left the`#[rust_const_unstable]` in `str::from_utf8_mut` (btw why is that one not const stable yet with rust-lang#57349 merged?). is there a way to redirect users to the stable `std::str::from_utf8` instead of only saying "hey this is unstable"? for now i just removed the check for `str::from_utf8` in the test in `tests/ui/suggestions/suggest-std-when-using-type.rs`.
2 parents a9730c3 + 15adc38 commit 805e0f4

File tree

4 files changed

+180
-22
lines changed

4 files changed

+180
-22
lines changed

library/core/src/str/mod.rs

+176
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,182 @@ impl str {
160160
self.len() == 0
161161
}
162162

163+
/// Converts a slice of bytes to a string slice.
164+
///
165+
/// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
166+
/// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
167+
/// the two. Not all byte slices are valid string slices, however: [`&str`] requires
168+
/// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
169+
/// UTF-8, and then does the conversion.
170+
///
171+
/// [`&str`]: str
172+
/// [byteslice]: prim@slice
173+
///
174+
/// If you are sure that the byte slice is valid UTF-8, and you don't want to
175+
/// incur the overhead of the validity check, there is an unsafe version of
176+
/// this function, [`from_utf8_unchecked`], which has the same
177+
/// behavior but skips the check.
178+
///
179+
/// If you need a `String` instead of a `&str`, consider
180+
/// [`String::from_utf8`][string].
181+
///
182+
/// [string]: ../std/string/struct.String.html#method.from_utf8
183+
///
184+
/// Because you can stack-allocate a `[u8; N]`, and you can take a
185+
/// [`&[u8]`][byteslice] of it, this function is one way to have a
186+
/// stack-allocated string. There is an example of this in the
187+
/// examples section below.
188+
///
189+
/// [byteslice]: slice
190+
///
191+
/// # Errors
192+
///
193+
/// Returns `Err` if the slice is not UTF-8 with a description as to why the
194+
/// provided slice is not UTF-8.
195+
///
196+
/// # Examples
197+
///
198+
/// Basic usage:
199+
///
200+
/// ```
201+
/// use std::str;
202+
///
203+
/// // some bytes, in a vector
204+
/// let sparkle_heart = vec![240, 159, 146, 150];
205+
///
206+
/// // We can use the ? (try) operator to check if the bytes are valid
207+
/// let sparkle_heart = str::from_utf8(&sparkle_heart)?;
208+
///
209+
/// assert_eq!("💖", sparkle_heart);
210+
/// # Ok::<_, str::Utf8Error>(())
211+
/// ```
212+
///
213+
/// Incorrect bytes:
214+
///
215+
/// ```
216+
/// use std::str;
217+
///
218+
/// // some invalid bytes, in a vector
219+
/// let sparkle_heart = vec![0, 159, 146, 150];
220+
///
221+
/// assert!(str::from_utf8(&sparkle_heart).is_err());
222+
/// ```
223+
///
224+
/// See the docs for [`Utf8Error`] for more details on the kinds of
225+
/// errors that can be returned.
226+
///
227+
/// A "stack allocated string":
228+
///
229+
/// ```
230+
/// use std::str;
231+
///
232+
/// // some bytes, in a stack-allocated array
233+
/// let sparkle_heart = [240, 159, 146, 150];
234+
///
235+
/// // We know these bytes are valid, so just use `unwrap()`.
236+
/// let sparkle_heart: &str = str::from_utf8(&sparkle_heart).unwrap();
237+
///
238+
/// assert_eq!("💖", sparkle_heart);
239+
/// ```
240+
#[unstable(feature = "inherent_str_constructors", issue = "131114")]
241+
pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
242+
converts::from_utf8(v)
243+
}
244+
245+
/// Converts a mutable slice of bytes to a mutable string slice.
246+
///
247+
/// # Examples
248+
///
249+
/// Basic usage:
250+
///
251+
/// ```
252+
/// use std::str;
253+
///
254+
/// // "Hello, Rust!" as a mutable vector
255+
/// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
256+
///
257+
/// // As we know these bytes are valid, we can use `unwrap()`
258+
/// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
259+
///
260+
/// assert_eq!("Hello, Rust!", outstr);
261+
/// ```
262+
///
263+
/// Incorrect bytes:
264+
///
265+
/// ```
266+
/// use std::str;
267+
///
268+
/// // Some invalid bytes in a mutable vector
269+
/// let mut invalid = vec![128, 223];
270+
///
271+
/// assert!(str::from_utf8_mut(&mut invalid).is_err());
272+
/// ```
273+
/// See the docs for [`Utf8Error`] for more details on the kinds of
274+
/// errors that can be returned.
275+
#[unstable(feature = "inherent_str_constructors", issue = "131114")]
276+
#[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
277+
pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
278+
converts::from_utf8_mut(v)
279+
}
280+
281+
/// Converts a slice of bytes to a string slice without checking
282+
/// that the string contains valid UTF-8.
283+
///
284+
/// See the safe version, [`from_utf8`], for more information.
285+
///
286+
/// # Safety
287+
///
288+
/// The bytes passed in must be valid UTF-8.
289+
///
290+
/// # Examples
291+
///
292+
/// Basic usage:
293+
///
294+
/// ```
295+
/// use std::str;
296+
///
297+
/// // some bytes, in a vector
298+
/// let sparkle_heart = vec![240, 159, 146, 150];
299+
///
300+
/// let sparkle_heart = unsafe {
301+
/// str::from_utf8_unchecked(&sparkle_heart)
302+
/// };
303+
///
304+
/// assert_eq!("💖", sparkle_heart);
305+
/// ```
306+
#[inline]
307+
#[must_use]
308+
#[unstable(feature = "inherent_str_constructors", issue = "131114")]
309+
pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
310+
// SAFETY: converts::from_utf8_unchecked has the same safety requirements as this function.
311+
unsafe { converts::from_utf8_unchecked(v) }
312+
}
313+
314+
/// Converts a slice of bytes to a string slice without checking
315+
/// that the string contains valid UTF-8; mutable version.
316+
///
317+
/// See the immutable version, [`from_utf8_unchecked()`] for more information.
318+
///
319+
/// # Examples
320+
///
321+
/// Basic usage:
322+
///
323+
/// ```
324+
/// use std::str;
325+
///
326+
/// let mut heart = vec![240, 159, 146, 150];
327+
/// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
328+
///
329+
/// assert_eq!("💖", heart);
330+
/// ```
331+
#[inline]
332+
#[must_use]
333+
#[unstable(feature = "inherent_str_constructors", issue = "131114")]
334+
pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
335+
// SAFETY: converts::from_utf8_unchecked_mut has the same safety requirements as this function.
336+
unsafe { converts::from_utf8_unchecked_mut(v) }
337+
}
338+
163339
/// Checks that `index`-th byte is the first byte in a UTF-8 code point
164340
/// sequence or the end of the string.
165341
///
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
//@ run-rustfix
22
fn main() {
33
let pi = std::f32::consts::PI; //~ ERROR ambiguous associated type
4-
let bytes = "hello world".as_bytes();
5-
let string = std::str::from_utf8(bytes).unwrap();
6-
//~^ ERROR no function or associated item named `from_utf8` found
7-
println!("{pi} {bytes:?} {string}");
4+
println!("{pi}");
85
}
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
//@ run-rustfix
22
fn main() {
33
let pi = f32::consts::PI; //~ ERROR ambiguous associated type
4-
let bytes = "hello world".as_bytes();
5-
let string = str::from_utf8(bytes).unwrap();
6-
//~^ ERROR no function or associated item named `from_utf8` found
7-
println!("{pi} {bytes:?} {string}");
4+
println!("{pi}");
85
}

tests/ui/suggestions/suggest-std-when-using-type.stderr

+2-14
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,6 @@ help: you are looking for the module in `std`, not the primitive type
99
LL | let pi = std::f32::consts::PI;
1010
| +++++
1111

12-
error[E0599]: no function or associated item named `from_utf8` found for type `str` in the current scope
13-
--> $DIR/suggest-std-when-using-type.rs:5:23
14-
|
15-
LL | let string = str::from_utf8(bytes).unwrap();
16-
| ^^^^^^^^^ function or associated item not found in `str`
17-
|
18-
help: you are looking for the module in `std`, not the primitive type
19-
|
20-
LL | let string = std::str::from_utf8(bytes).unwrap();
21-
| +++++
22-
23-
error: aborting due to 2 previous errors
12+
error: aborting due to 1 previous error
2413

25-
Some errors have detailed explanations: E0223, E0599.
26-
For more information about an error, try `rustc --explain E0223`.
14+
For more information about this error, try `rustc --explain E0223`.

0 commit comments

Comments
 (0)