|
1 | 1 | //! Ways to create a `str` from bytes slice.
|
2 | 2 |
|
3 |
| -use crate::mem; |
| 3 | +use crate::{mem, ptr}; |
4 | 4 |
|
5 | 5 | use super::validations::run_utf8_validation;
|
6 | 6 | use super::Utf8Error;
|
@@ -205,3 +205,41 @@ pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
|
205 | 205 | // comes from a reference which is guaranteed to be valid for writes.
|
206 | 206 | unsafe { &mut *(v as *mut [u8] as *mut str) }
|
207 | 207 | }
|
| 208 | + |
| 209 | +/// Creates an `&str` from a pointer and a length. |
| 210 | +/// |
| 211 | +/// The pointed-to bytes must be valid UTF-8. |
| 212 | +/// If this might not be the case, use `str::from_utf8(slice::from_raw_parts(ptr, len))`, |
| 213 | +/// which will return an `Err` if the data isn't valid UTF-8. |
| 214 | +/// |
| 215 | +/// This function is the `str` equivalent of [`slice::from_raw_parts`](crate::slice::from_raw_parts). |
| 216 | +/// See that function's documentation for safety concerns and examples. |
| 217 | +/// |
| 218 | +/// The mutable version of this function is [`from_raw_parts_mut`]. |
| 219 | +#[inline] |
| 220 | +#[must_use] |
| 221 | +#[unstable(feature = "str_from_raw_parts", issue = "119206")] |
| 222 | +#[rustc_const_unstable(feature = "str_from_raw_parts", issue = "119206")] |
| 223 | +pub const unsafe fn from_raw_parts<'a>(ptr: *const u8, len: usize) -> &'a str { |
| 224 | + // SAFETY: the caller must uphold the safety contract for `from_raw_parts`. |
| 225 | + unsafe { &*ptr::from_raw_parts(ptr.cast(), len) } |
| 226 | +} |
| 227 | + |
| 228 | +/// Creates an `&mut str` from a pointer and a length. |
| 229 | +/// |
| 230 | +/// The pointed-to bytes must be valid UTF-8. |
| 231 | +/// If this might not be the case, use `str::from_utf8_mut(slice::from_raw_parts_mut(ptr, len))`, |
| 232 | +/// which will return an `Err` if the data isn't valid UTF-8. |
| 233 | +/// |
| 234 | +/// This function is the `str` equivalent of [`slice::from_raw_parts_mut`](crate::slice::from_raw_parts_mut). |
| 235 | +/// See that function's documentation for safety concerns and examples. |
| 236 | +/// |
| 237 | +/// The immutable version of this function is [`from_raw_parts`]. |
| 238 | +#[inline] |
| 239 | +#[must_use] |
| 240 | +#[unstable(feature = "str_from_raw_parts", issue = "119206")] |
| 241 | +#[rustc_const_unstable(feature = "const_str_from_raw_parts_mut", issue = "119206")] |
| 242 | +pub const unsafe fn from_raw_parts_mut<'a>(ptr: *mut u8, len: usize) -> &'a str { |
| 243 | + // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`. |
| 244 | + unsafe { &mut *ptr::from_raw_parts_mut(ptr.cast(), len) } |
| 245 | +} |
0 commit comments