Skip to content

Commit 757a5a3

Browse files
committed
Move deserialize
1 parent e31d65a commit 757a5a3

2 files changed

Lines changed: 23 additions & 24 deletions

File tree

src/decode.rs

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,29 @@ use std::os::raw::c_char;
1313

1414
import_exception!(json, JSONDecodeError);
1515

16-
pub fn deserialize(py: Python, data: &str) -> PyResult<PyObject> {
16+
pub fn deserialize(py: Python, obj: PyObject) -> PyResult<PyObject> {
17+
let obj_ref = obj.as_ref(py);
18+
let obj_ptr = obj_ref.get_type_ptr();
19+
let data: Cow<str>;
20+
if unsafe { obj_ptr == typeref::STR_PTR } {
21+
data = unsafe {
22+
Cow::Borrowed(std::str::from_utf8_unchecked(
23+
<PyUnicode as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes(),
24+
))
25+
};
26+
} else if unsafe { obj_ptr == typeref::BYTES_PTR } {
27+
data = String::from_utf8_lossy(unsafe {
28+
<PyBytes as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes()
29+
});
30+
} else {
31+
return Err(pyo3::exceptions::TypeError::py_err(format!(
32+
"Input must be str or bytes, not: {}",
33+
obj_ref.get_type().name()
34+
)));
35+
}
36+
1737
let seed = JsonValue::new(py);
18-
let mut deserializer = serde_json::Deserializer::from_str(data);
38+
let mut deserializer = serde_json::Deserializer::from_str(&data);
1939
match seed.deserialize(&mut deserializer) {
2040
Ok(py_ptr) => {
2141
deserializer

src/lib.rs

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@ extern crate pyo3;
99
extern crate serde;
1010
extern crate serde_json;
1111
extern crate smallvec;
12-
use std::borrow::Cow;
1312

1413
use pyo3::prelude::*;
15-
use pyo3::types::*;
1614

1715
mod decode;
1816
mod encode;
@@ -34,26 +32,7 @@ fn orjson(py: Python, m: &PyModule) -> PyResult<()> {
3432
/// Deserialize JSON to Python objects.
3533
#[pyfunction]
3634
pub fn loads(py: Python, obj: PyObject) -> PyResult<PyObject> {
37-
let obj_ref = obj.as_ref(py);
38-
let obj_ptr = obj_ref.get_type_ptr();
39-
let val: Cow<str>;
40-
if unsafe { obj_ptr == typeref::STR_PTR } {
41-
val = unsafe {
42-
Cow::Borrowed(std::str::from_utf8_unchecked(
43-
<PyUnicode as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes(),
44-
))
45-
};
46-
} else if unsafe { obj_ptr == typeref::BYTES_PTR } {
47-
val = String::from_utf8_lossy(unsafe {
48-
<PyBytes as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes()
49-
});
50-
} else {
51-
return Err(pyo3::exceptions::TypeError::py_err(format!(
52-
"Input must be str or bytes, not: {}",
53-
obj_ref.get_type().name()
54-
)));
55-
}
56-
decode::deserialize(py, &val)
35+
decode::deserialize(py, obj)
5736
}
5837

5938
/// dumps(obj, /)

0 commit comments

Comments
 (0)