Skip to content

Commit

Permalink
RString::to_string: use Ruby cached utf-8 validity when available
Browse files Browse the repository at this point in the history
  • Loading branch information
matsadler committed Jan 20, 2025
1 parent 6a0b737 commit f1e8bd6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
nanosecond precision.
- 'old-api' feature, which disables deprecation warnings for the old api is no
longer a default feature.
- `RString::to_string` will now use a Ruby utf-8 validation api that caches the
results of the validity check. This will greatly improve performance in the
case a string is already known to be utf-8, but may slightly reduce
performance when not known.

### Deprecated

Expand Down
15 changes: 7 additions & 8 deletions src/r_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,14 +1165,13 @@ impl RString {
/// ```
pub fn to_string(self) -> Result<String, Error> {
let handle = Ruby::get_with(self);
let utf8 = if self.is_utf8_compatible_encoding() {
self
} else {
self.conv_enc(handle.utf8_encoding())?
};
str::from_utf8(unsafe { utf8.as_slice() })
.map(ToOwned::to_owned)
.map_err(|e| Error::new(handle.exception_encoding_error(), format!("{}", e)))
unsafe {
if let Some(str) = self.test_as_str() {
Ok(str.to_owned())
} else {
Ok(self.conv_enc(handle.utf8_encoding())?.as_str()?.to_owned())
}
}
}

/// Returns `self` as an owned Rust `Bytes`.
Expand Down

0 comments on commit f1e8bd6

Please sign in to comment.