Skip to content
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

add PyStringMethods::encode_utf8 #3801

Merged
merged 1 commit into from
Feb 10, 2024
Merged
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
1 change: 1 addition & 0 deletions newsfragments/3801.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `PyStringMethods::encode_utf8`.
39 changes: 34 additions & 5 deletions src/types/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ pub trait PyStringMethods<'py> {
/// replaced with `U+FFFD REPLACEMENT CHARACTER`.
fn to_string_lossy(&self) -> Cow<'_, str>;

/// Encodes this string as a Python `bytes` object, using UTF-8 encoding.
fn encode_utf8(&self) -> PyResult<Bound<'py, PyBytes>>;

/// Obtains the raw data backing the Python string.
///
/// If the Python string object was created through legacy APIs, its internal storage format
Expand Down Expand Up @@ -337,6 +340,14 @@ impl<'py> PyStringMethods<'py> for Bound<'py, PyString> {
self.as_borrowed().to_string_lossy()
}

fn encode_utf8(&self) -> PyResult<Bound<'py, PyBytes>> {
unsafe {
ffi::PyUnicode_AsUTF8String(self.as_ptr())
.assume_owned_or_err(self.py())
.downcast_into_unchecked::<PyBytes>()
}
}

#[cfg(not(Py_LIMITED_API))]
unsafe fn data(&self) -> PyResult<PyStringData<'_>> {
self.as_borrowed().data()
Expand Down Expand Up @@ -371,11 +382,7 @@ impl<'a> Borrowed<'a, '_, PyString> {

#[cfg(not(any(Py_3_10, not(Py_LIMITED_API))))]
{
let bytes = unsafe {
ffi::PyUnicode_AsUTF8String(self.as_ptr())
.assume_owned_or_err(self.py())?
.downcast_into_unchecked::<PyBytes>()
};
let bytes = self.encode_utf8()?;
Ok(Cow::Owned(
unsafe { str::from_utf8_unchecked(bytes.as_bytes()) }.to_owned(),
))
Expand Down Expand Up @@ -535,6 +542,28 @@ mod tests {
})
}

#[test]
fn test_encode_utf8_unicode() {
Python::with_gil(|py| {
let s = "哈哈🐈";
let obj = PyString::new_bound(py, s);
assert_eq!(s.as_bytes(), obj.encode_utf8().unwrap().as_bytes());
})
}

#[test]
fn test_encode_utf8_surrogate() {
Python::with_gil(|py| {
let obj: PyObject = py.eval(r"'\ud800'", None, None).unwrap().into();
assert!(obj
.bind(py)
.downcast::<PyString>()
.unwrap()
.encode_utf8()
.is_err());
})
}

#[test]
fn test_to_string_lossy() {
Python::with_gil(|py| {
Expand Down
Loading