Skip to content

str: Mark unstable round_char_boundary feature functions as const #144472

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

Merged
merged 1 commit into from
Jul 28, 2025
Merged
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
40 changes: 26 additions & 14 deletions library/core/src/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,17 +407,22 @@ impl str {
/// ```
#[unstable(feature = "round_char_boundary", issue = "93743")]
#[inline]
pub fn floor_char_boundary(&self, index: usize) -> usize {
pub const fn floor_char_boundary(&self, index: usize) -> usize {
if index >= self.len() {
self.len()
} else {
let lower_bound = index.saturating_sub(3);
let new_index = self.as_bytes()[lower_bound..=index]
.iter()
.rposition(|b| b.is_utf8_char_boundary());

// SAFETY: we know that the character boundary will be within four bytes
unsafe { lower_bound + new_index.unwrap_unchecked() }
let mut i = index;
while i > 0 {
if self.as_bytes()[i].is_utf8_char_boundary() {
break;
}
i -= 1;
}

// The character boundary will be within four bytes of the index
debug_assert!(i >= index.saturating_sub(3));

i
}
}

Expand Down Expand Up @@ -445,15 +450,22 @@ impl str {
/// ```
#[unstable(feature = "round_char_boundary", issue = "93743")]
#[inline]
pub fn ceil_char_boundary(&self, index: usize) -> usize {
pub const fn ceil_char_boundary(&self, index: usize) -> usize {
if index >= self.len() {
self.len()
} else {
let upper_bound = Ord::min(index + 4, self.len());
self.as_bytes()[index..upper_bound]
.iter()
.position(|b| b.is_utf8_char_boundary())
.map_or(upper_bound, |pos| pos + index)
let mut i = index;
while i < self.len() {
if self.as_bytes()[i].is_utf8_char_boundary() {
break;
}
i += 1;
}

// The character boundary will be within four bytes of the index
debug_assert!(i <= index + 3);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Personally, I think that simply adding this as a condition to the loop itself might be helpful (and similarly above) to ensure that the optimiser knows this precondition as well. Not sure how it'd affect codegen, but it feels like the safest approach compared to, for example, assert_unchecked.


i
}
}

Expand Down
Loading