Skip to content

Commit 038e93b

Browse files
committed
Simplify deserialize input
1 parent 2c473a5 commit 038e93b

2 files changed

Lines changed: 16 additions & 17 deletions

File tree

src/decode.rs

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
use crate::typeref;
44
use pyo3::prelude::*;
5-
use pyo3::types::*;
65
use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
76
use smallvec::SmallVec;
87
use std::borrow::Cow;
@@ -12,25 +11,25 @@ use std::os::raw::c_char;
1211

1312
import_exception!(json, JSONDecodeError);
1413

15-
pub fn deserialize(py: Python, obj: PyObject) -> PyResult<PyObject> {
16-
let obj_ref = obj.as_ref(py);
17-
let obj_ptr = obj_ref.get_type_ptr();
14+
pub fn deserialize(py: Python, ptr: *mut pyo3::ffi::PyObject) -> PyResult<PyObject> {
15+
let obj_type_ptr = unsafe { (*ptr).ob_type };
1816
let data: Cow<str>;
19-
if unsafe { obj_ptr == typeref::STR_PTR } {
17+
if unsafe { obj_type_ptr == typeref::STR_PTR } {
18+
let mut str_size: pyo3::ffi::Py_ssize_t = unsafe { std::mem::uninitialized() };
2019
data = unsafe {
21-
Cow::Borrowed(std::str::from_utf8_unchecked(
22-
<PyUnicode as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes(),
23-
))
20+
Cow::Borrowed(std::str::from_utf8_unchecked(std::slice::from_raw_parts(
21+
pyo3::ffi::PyUnicode_AsUTF8AndSize(ptr, &mut str_size) as *const u8,
22+
str_size as usize,
23+
)))
2424
};
25-
} else if unsafe { obj_ptr == typeref::BYTES_PTR } {
26-
data = String::from_utf8_lossy(unsafe {
27-
<PyBytes as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes()
28-
});
25+
} else if unsafe { obj_type_ptr == typeref::BYTES_PTR } {
26+
let buffer = unsafe { pyo3::ffi::PyBytes_AsString(ptr) as *const u8 };
27+
let length = unsafe { pyo3::ffi::PyBytes_Size(ptr) as usize };
28+
data = unsafe { String::from_utf8_lossy(std::slice::from_raw_parts(buffer, length)) };
2929
} else {
30-
return Err(pyo3::exceptions::TypeError::py_err(format!(
31-
"Input must be str or bytes, not: {}",
32-
obj_ref.get_type().name()
33-
)));
30+
return Err(pyo3::exceptions::TypeError::py_err(
31+
"Input must be str or bytes",
32+
));
3433
}
3534

3635
let seed = JsonValue::new();

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ fn orjson(py: Python, m: &PyModule) -> PyResult<()> {
3333
/// Deserialize JSON to Python objects.
3434
#[pyfunction]
3535
pub fn loads(py: Python, obj: PyObject) -> PyResult<PyObject> {
36-
decode::deserialize(py, obj)
36+
decode::deserialize(py, obj.as_ptr())
3737
}
3838

3939
/// dumps(obj, /)

0 commit comments

Comments
 (0)