diff --git a/src/types/string.rs b/src/types/string.rs index 8e313edc..2bb5e3cd 100644 --- a/src/types/string.rs +++ b/src/types/string.rs @@ -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::(data); + Ok(std::str::from_utf8_unchecked(bytes.as_bytes())) + } + } } /// Converts the `PyString` into a Rust string.