Skip to content

Commit

Permalink
Deduplicate std::string -> C string conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Feb 5, 2025
1 parent 6a217fc commit 684c07e
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 7 deletions.
4 changes: 0 additions & 4 deletions src/cxx.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,6 @@ const char *cxxbridge1$cxx_string$data(const std::string &s) noexcept {
return s.data();
}

const char *cxxbridge1$cxx_string$c_str(const std::string &s) noexcept {
return s.c_str();
}

std::size_t cxxbridge1$cxx_string$length(const std::string &s) noexcept {
return s.length();
}
Expand Down
5 changes: 2 additions & 3 deletions src/cxx_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ extern "C" {
fn string_destroy(this: &mut MaybeUninit<CxxString>);
#[link_name = "cxxbridge1$cxx_string$data"]
fn string_data(this: &CxxString) -> *const u8;
#[link_name = "cxxbridge1$cxx_string$c_str"]
fn string_c_str(this: &CxxString) -> *const c_char;
#[link_name = "cxxbridge1$cxx_string$length"]
fn string_length(this: &CxxString) -> usize;
#[link_name = "cxxbridge1$cxx_string$clear"]
Expand Down Expand Up @@ -146,7 +144,8 @@ impl CxxString {

/// Produces a `&CStr` view of the string without additional allocations.
pub fn as_c_str(&self) -> &CStr {
unsafe { CStr::from_ptr(string_c_str(self)) }
// Since C++11, string[string.size()] is guaranteed to be \0.
unsafe { CStr::from_ptr(self.as_ptr().cast::<c_char>()) }
}

/// If the contents of the C++ string are valid UTF-8, this function returns
Expand Down

0 comments on commit 684c07e

Please sign in to comment.