Skip to content

Commit

Permalink
fix error handling code
Browse files Browse the repository at this point in the history
  • Loading branch information
Robin committed Jun 13, 2022
1 parent b34be4b commit 53b4bf3
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/types/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ impl<'a> PyStringData<'a> {
/// C APIs that skip input validation (like `PyUnicode_FromKindAndData`) and should
/// never occur for strings that were created from Python code.
pub fn to_string(self, py: Python<'_>) -> PyResult<Cow<'a, str>> {
use std::ffi::CStr;
match self {
Self::Ucs1(data) => match str::from_utf8(data) {
Ok(s) => Ok(Cow::Borrowed(s)),
Expand Down Expand Up @@ -236,15 +235,17 @@ impl PyString {
let len = ffi::PyUnicode_GetLength(self.as_ptr());
(0..len).map(move |i| {
let c = ffi::PyUnicode_ReadChar(self.as_ptr(), i);
char::from_u32(c).ok_or_else(|| {
exceptions::PyUnicodeDecodeError::new(
match char::from_u32(c) {
Some(c) => Ok(c),
None => Err(exceptions::PyUnicodeDecodeError::new(
self.py(),
CStr::from_bytes_with_nul(b"utf-8\0").unwrap(),
&c.to_ne_bytes(),
i as usize..(i + 1) as usize,
CStr::from_bytes_with_nul(b"invalid codepoint\0").unwrap(),
)
})
)?
.into()),
}
})
}
}
Expand Down

0 comments on commit 53b4bf3

Please sign in to comment.