From 1b2d26794a218f5f09dc0061996617cd083d5663 Mon Sep 17 00:00:00 2001 From: Alex Gaynor Date: Mon, 14 Sep 2020 22:11:00 -0400 Subject: [PATCH] Make unicode handling abi3 friendly --- src/types/string.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) 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.