Document UTF-8 FFI assumptions

This commit is contained in:
ijl 2018-09-28 22:01:04 +00:00
parent 851d2207c0
commit 38c6d942b7
2 changed files with 4 additions and 0 deletions

View file

@ -56,6 +56,8 @@ impl PyString {
unsafe {
let mut size: ffi::Py_ssize_t = mem::uninitialized();
let data = ffi::PyUnicode_AsUTF8AndSize(self.0.as_ptr(), &mut size) as *const u8;
// PyUnicode_AsUTF8AndSize would return null if the pointer did not reference a valid
// unicode object, but because we have a valid PyString, assume success
debug_assert!(!data.is_null());
std::slice::from_raw_parts(data, size as usize)
}

View file

@ -154,6 +154,8 @@ impl PyUnicode {
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe {
// PyUnicode_AsUTF8String would return null if the pointer did not reference a valid
// unicode object, but because we have a valid PyUnicode, assume success
let data: Py<PyBytes> = Py::from_owned_ptr(
ffi::PyUnicode_AsUTF8String(self.0.as_ptr()),
);