Skip to content
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
3 changes: 2 additions & 1 deletion library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,8 @@ impl CStr {
#[stable(feature = "cstr_count_bytes", since = "1.79.0")]
#[rustc_const_stable(feature = "const_cstr_from_ptr", since = "1.81.0")]
pub const fn count_bytes(&self) -> usize {
self.inner.len() - 1
// SAFETY: This length includes the nul-terminator, so it's at least one.
unsafe { self.inner.len().unchecked_sub(1) }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think I'm OK with this. An alternative could be to try to_bytes().len(), which technically should/could avoid the panic (to_bytes_with_nul, which it calls, has an assert_unchecked(!empty)).

But the added indirection doesn't seem like it has a ton of value and probably hurts optimization (at least in terms of how long it takes to compile).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

assert_unchecked does actually hurt a lot more than it helps, so, the unchecked sub should just help convey the length information properly, honestly.

}

/// Returns `true` if `self.to_bytes()` has a length of 0.
Expand Down
Loading