Skip to content

Add str pointer methods #85816

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,9 @@ language_item_table! {
ConstPtr, sym::const_ptr, const_ptr_impl, Target::Impl, GenericRequirement::None;
MutPtr, sym::mut_ptr, mut_ptr_impl, Target::Impl, GenericRequirement::None;
ConstSlicePtr, sym::const_slice_ptr, const_slice_ptr_impl, Target::Impl, GenericRequirement::None;
ConstStrPtr, sym::const_str_ptr, const_str_ptr_impl, Target::Impl, GenericRequirement::None;
MutSlicePtr, sym::mut_slice_ptr, mut_slice_ptr_impl, Target::Impl, GenericRequirement::None;
MutStrPtr, sym::mut_str_ptr, mut_str_ptr_impl, Target::Impl, GenericRequirement::None;
I8, sym::i8, i8_impl, Target::Impl, GenericRequirement::None;
I16, sym::i16, i16_impl, Target::Impl, GenericRequirement::None;
I32, sym::i32, i32_impl, Target::Impl, GenericRequirement::None;
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ symbols! {
const_raw_ptr_to_usize_cast,
const_refs_to_cell,
const_slice_ptr,
const_str_ptr,
const_trait_bound_opt_out,
const_trait_impl,
const_transmute,
Expand Down Expand Up @@ -839,6 +840,7 @@ symbols! {
must_use,
mut_ptr,
mut_slice_ptr,
mut_str_ptr,
naked,
naked_functions,
name,
Expand Down
19 changes: 12 additions & 7 deletions compiler/rustc_typeck/src/check/method/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -680,16 +680,21 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
self.assemble_inherent_impl_for_primitive(lang_def_id);
}
ty::RawPtr(ty::TypeAndMut { ty: _, mutbl }) => {
let (lang_def_id1, lang_def_id2) = match mutbl {
hir::Mutability::Not => {
(lang_items.const_ptr_impl(), lang_items.const_slice_ptr_impl())
}
hir::Mutability::Mut => {
(lang_items.mut_ptr_impl(), lang_items.mut_slice_ptr_impl())
}
let (lang_def_id1, lang_def_id2, lang_def_id3) = match mutbl {
hir::Mutability::Not => (
lang_items.const_ptr_impl(),
lang_items.const_slice_ptr_impl(),
lang_items.const_str_ptr_impl(),
),
hir::Mutability::Mut => (
lang_items.mut_ptr_impl(),
lang_items.mut_slice_ptr_impl(),
lang_items.mut_str_ptr_impl(),
),
};
self.assemble_inherent_impl_for_primitive(lang_def_id1);
self.assemble_inherent_impl_for_primitive(lang_def_id2);
self.assemble_inherent_impl_for_primitive(lang_def_id3);
}
ty::Int(i) => {
let lang_def_id = match i {
Expand Down
26 changes: 26 additions & 0 deletions compiler/rustc_typeck/src/coherence/inherent_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,19 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> {
assoc_items,
);
}
ty::RawPtr(ty::TypeAndMut { ty: inner, mutbl: hir::Mutability::Not })
if matches!(inner.kind(), ty::Str) =>
{
self.check_primitive_impl(
item.def_id,
lang_items.const_str_ptr_impl(),
None,
"const_str_ptr",
"*const str",
item.span,
assoc_items,
);
}
ty::RawPtr(ty::TypeAndMut { ty: inner, mutbl: hir::Mutability::Mut })
if matches!(inner.kind(), ty::Slice(_)) =>
{
Expand All @@ -163,6 +176,19 @@ impl ItemLikeVisitor<'v> for InherentCollect<'tcx> {
assoc_items,
);
}
ty::RawPtr(ty::TypeAndMut { ty: inner, mutbl: hir::Mutability::Mut })
if matches!(inner.kind(), ty::Str) =>
{
self.check_primitive_impl(
item.def_id,
lang_items.mut_str_ptr_impl(),
None,
"mut_str_ptr",
"*mut str",
item.span,
assoc_items,
);
}
ty::RawPtr(ty::TypeAndMut { ty: _, mutbl: hir::Mutability::Not }) => {
self.check_primitive_impl(
item.def_id,
Expand Down
5 changes: 5 additions & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@
#![feature(const_type_name)]
#![feature(const_unreachable_unchecked)]
#![feature(const_default_impls)]
#![feature(const_str_from_raw_parts)]
#![cfg_attr(not(bootstrap), feature(const_str_ptr_len))]
#![feature(duration_consts_2)]
#![feature(ptr_metadata)]
#![feature(slice_ptr_get)]
Expand Down Expand Up @@ -156,6 +158,9 @@
#![feature(simd_ffi)]
#![feature(staged_api)]
#![feature(stmt_expr_attributes)]
#![cfg_attr(not(bootstrap), feature(str_ptr_len))]
#![cfg_attr(not(bootstrap), feature(str_ptr_as_ptr))]
#![cfg_attr(not(bootstrap), feature(str_ptr_get))]
#![feature(trait_alias)]
#![feature(transparent_unions)]
#![feature(try_blocks)]
Expand Down
79 changes: 79 additions & 0 deletions library/core/src/ptr/const_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,85 @@ impl<T> *const [T] {
}
}

#[cfg(not(bootstrap))]
#[lang = "const_str_ptr"]
impl *const str {
/// Returns the length of a raw string slice.
///
/// The returned value is the number of **bytes**, not the number of characters.
///
/// This function is safe, even when the raw string slice cannot be cast to a slice
/// reference because the pointer is null or unaligned.
///
/// # Examples
///
/// ```rust
/// #![feature(str_ptr_len)]
/// #![feature(str_from_raw_parts)]
///
/// use std::ptr;
///
/// let str: *const str = ptr::str_from_raw_parts(ptr::null(), 3);
/// assert_eq!(str.len(), 3);
/// ```
#[inline]
#[unstable(feature = "str_ptr_len", issue = "none")]
#[rustc_const_unstable(feature = "const_str_ptr_len", issue = "none")]
pub const fn len(self) -> usize {
metadata(self)
}

/// Returns a raw pointer to the string slice's buffer.
///
/// This is equivalent to casting `self` to `*const u8`, but more type-safe.
///
/// # Examples
///
/// ```rust
/// #![feature(str_ptr_as_ptr)]
/// #![feature(str_from_raw_parts)]
/// use std::ptr;
///
/// let str: *const str = ptr::str_from_raw_parts(ptr::null(), 3);
/// assert_eq!(str.as_ptr(), 0 as *const u8);
/// ```
#[inline]
#[unstable(feature = "str_ptr_as_ptr", issue = "none")]
#[rustc_const_unstable(feature = "str_ptr_as_ptr", issue = "none")]
pub const fn as_ptr(self) -> *const u8 {
self as *const u8
}

/// Returns a raw pointer to an substring, without doing bounds
/// checking.
///
/// Calling this method with an out-of-bounds index, index that does not lie on an UTF-8 sequence boundaries or when `self` is not dereferencable
/// is *[undefined behavior]* even if the resulting pointer is not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// #![feature(str_ptr_get)]
///
/// let x = "abc" as *const str;
///
/// unsafe {
/// assert_eq!(&*x.get_unchecked(1..), "bc");
/// }
/// ```
#[unstable(feature = "str_ptr_get", issue = "none")]
#[inline]
pub unsafe fn get_unchecked<I>(self, index: I) -> *const I::Output
where
I: SliceIndex<str>,
{
// SAFETY: the caller ensures that `self` is dereferencable, `index` in-bounds and lie on an UTF-8 sequence boundaries.
unsafe { index.get_unchecked(self) }
}
}

// Equality for pointers
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> PartialEq for *const T {
Expand Down
63 changes: 63 additions & 0 deletions library/core/src/ptr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,69 @@ pub const fn slice_from_raw_parts_mut<T>(data: *mut T, len: usize) -> *mut [T] {
from_raw_parts_mut(data.cast(), len)
}

/// Forms a raw string slice from a pointer and a length.
///
/// The `len` argument is the number of **bytes**, not the number of characters.
///
/// This function is safe, but actually using the return value is unsafe.
/// See the documentation of [`slice::from_raw_parts`] for slice safety requirements and [`str::from_utf8`] for string safety requirements.
///
/// [`slice::from_raw_parts`]: crate::slice::from_raw_parts
/// [`str::from_utf8`]: crate::str::from_utf8
///
/// # Examples
///
/// ```rust
/// #![feature(str_from_raw_parts)]
/// use std::ptr;
///
/// // create a string slice pointer when starting out with a pointer to the first element
/// let x = "abc";
/// let raw_pointer = x.as_ptr();
/// let str = ptr::str_from_raw_parts(raw_pointer, 3);
/// assert_eq!(unsafe { &*str }, x);
/// ```
#[inline]
#[unstable(feature = "str_from_raw_parts", issue = "none")]
#[rustc_const_unstable(feature = "const_str_from_raw_parts", issue = "none")]
pub const fn str_from_raw_parts(data: *const u8, len: usize) -> *const str {
from_raw_parts(data.cast(), len)
}

/// Performs the same functionality as [`str_from_raw_parts`], except that a
/// raw mutable string slice is returned, as opposed to a raw immutable string slice.
///
/// See the documentation of [`slice_from_raw_parts`] for more details.
///
/// This function is safe, but actually using the return value is unsafe.
/// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements and [`str::from_utf8_mut`] for string safety requirements.
///
/// [`slice::from_raw_parts_mut`]: crate::slice::from_raw_parts_mut
/// [`str::from_utf8_mut`]: crate::str::from_utf8_mut
///
/// # Examples
///
/// ```rust
/// #![feature(str_from_raw_parts)]
/// use std::ptr;
///
/// let mut x = [b'a', b'b', b'c'];
/// let raw_pointer = x.as_mut_ptr();
/// let str = ptr::str_from_raw_parts_mut(raw_pointer, 3);
///
/// unsafe {
/// (*(str as *mut [u8]))[2] = b'z'; // assign a value at an index in the string slice
/// };
///
/// assert_eq!(unsafe { &*str }, "abz");
/// ```
#[inline]
#[unstable(feature = "str_from_raw_parts", issue = "none")]
#[rustc_const_unstable(feature = "const_str_from_raw_parts", issue = "none")]
pub const fn str_from_raw_parts_mut(data: *mut u8, len: usize) -> *mut str {
from_raw_parts_mut(data.cast(), len)
}

/// Swaps the values at two mutable locations of the same type, without
/// deinitializing either.
///
Expand Down
81 changes: 81 additions & 0 deletions library/core/src/ptr/mut_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,87 @@ impl<T> *mut [T] {
}
}

#[cfg(not(bootstrap))]
#[lang = "mut_str_ptr"]
impl *mut str {
/// Returns the length of a raw string slice.
///
/// The returned value is the number of **bytes**, not the number of characters.
///
/// This function is safe, even when the raw string slice cannot be cast to a slice
/// reference because the pointer is null or unaligned.
///
/// # Examples
///
/// ```rust
/// #![feature(str_ptr_len)]
/// #![feature(str_from_raw_parts)]
///
/// use std::ptr;
///
/// let str: *mut str = ptr::str_from_raw_parts_mut(ptr::null_mut(), 3);
/// assert_eq!(str.len(), 3);
/// ```
#[inline]
#[unstable(feature = "str_ptr_len", issue = "none")]
#[rustc_const_unstable(feature = "const_str_ptr_len", issue = "none")]
pub const fn len(self) -> usize {
metadata(self)
}

/// Returns a raw pointer to the string slice's buffer.
///
/// This is equivalent to casting `self` to `*mut u8`, but more type-safe.
///
/// # Examples
///
/// ```rust
/// #![feature(str_ptr_as_ptr)]
/// #![feature(str_from_raw_parts)]
/// use std::ptr;
///
/// let str: *mut str = ptr::str_from_raw_parts_mut(ptr::null_mut(), 3);
/// assert_eq!(str.as_mut_ptr(), 0 as *mut u8);
/// ```
#[inline]
#[unstable(feature = "str_ptr_as_ptr", issue = "none")]
#[rustc_const_unstable(feature = "str_ptr_as_ptr", issue = "none")]
pub const fn as_mut_ptr(self) -> *mut u8 {
self as *mut u8
}

/// Returns a raw pointer to an substring, without doing bounds
/// checking.
///
/// Calling this method with an out-of-bounds index, index that does not lie on an UTF-8 sequence boundaries or when `self` is not dereferencable
/// is *[undefined behavior]* even if the resulting pointer is not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// #![feature(str_ptr_get)]
///
/// let mut x = [b'a', b'b', b'c'];
/// let x: &mut str = std::str::from_utf8_mut(&mut x).unwrap();
/// let x: *mut str = x as *mut str;
///
/// unsafe {
/// assert_eq!(&*x.get_unchecked_mut(1..), "bc");
/// }
/// ```
#[unstable(feature = "str_ptr_get", issue = "none")]
#[inline]
pub unsafe fn get_unchecked_mut<I>(self, index: I) -> *mut I::Output
where
I: SliceIndex<str>,
{
// SAFETY: the caller ensures that `self` is dereferencable, `index` in-bounds and lie on an UTF-8 sequence boundaries.
unsafe { index.get_unchecked_mut(self) }
}
}

// Equality for pointers
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> PartialEq for *mut T {
Expand Down
Loading