Merge pull request #1187 from alex/abi3-to-str

Make unicode handling abi3 friendly
This commit is contained in:
Yuji Kanagawa 2020-09-15 20:02:17 +09:00 committed by GitHub
commit 2ec1c3b0b9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -44,6 +44,7 @@ impl PyString {
/// (containing unpaired surrogates).
#[inline]
pub fn to_str(&self) -> PyResult<&str> {
#[cfg(not(Py_LIMITED_API))]
unsafe {
let mut size: ffi::Py_ssize_t = 0;
let data = ffi::PyUnicode_AsUTF8AndSize(self.as_ptr(), &mut size) as *const u8;
@ -54,6 +55,16 @@ impl PyString {
Ok(std::str::from_utf8_unchecked(slice))
}
}
#[cfg(Py_LIMITED_API)]
unsafe {
let data = ffi::PyUnicode_AsUTF8String(self.as_ptr());
if data.is_null() {
Err(PyErr::fetch(self.py()))
} else {
let bytes = self.py().from_owned_ptr::<PyBytes>(data);
Ok(std::str::from_utf8_unchecked(bytes.as_bytes()))
}
}
}
/// Converts the `PyString` into a Rust string.