Skip to content

Commit

Permalink
Simplify deserialize input
Browse files Browse the repository at this point in the history
  • Loading branch information
ijl committed Jan 2, 2019
1 parent 2c473a5 commit 038e93b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 17 deletions.
31 changes: 15 additions & 16 deletions src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use crate::typeref;
use pyo3::prelude::*;
use pyo3::types::*;
use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
use smallvec::SmallVec;
use std::borrow::Cow;
Expand All @@ -12,25 +11,25 @@ use std::os::raw::c_char;

import_exception!(json, JSONDecodeError);

pub fn deserialize(py: Python, obj: PyObject) -> PyResult<PyObject> {
let obj_ref = obj.as_ref(py);
let obj_ptr = obj_ref.get_type_ptr();
pub fn deserialize(py: Python, ptr: *mut pyo3::ffi::PyObject) -> PyResult<PyObject> {
let obj_type_ptr = unsafe { (*ptr).ob_type };
let data: Cow<str>;
if unsafe { obj_ptr == typeref::STR_PTR } {
if unsafe { obj_type_ptr == typeref::STR_PTR } {
let mut str_size: pyo3::ffi::Py_ssize_t = unsafe { std::mem::uninitialized() };
data = unsafe {
Cow::Borrowed(std::str::from_utf8_unchecked(
<PyUnicode as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes(),
))
Cow::Borrowed(std::str::from_utf8_unchecked(std::slice::from_raw_parts(
pyo3::ffi::PyUnicode_AsUTF8AndSize(ptr, &mut str_size) as *const u8,
str_size as usize,
)))
};
} else if unsafe { obj_ptr == typeref::BYTES_PTR } {
data = String::from_utf8_lossy(unsafe {
<PyBytes as PyTryFrom>::try_from_unchecked(obj_ref).as_bytes()
});
} else if unsafe { obj_type_ptr == typeref::BYTES_PTR } {
let buffer = unsafe { pyo3::ffi::PyBytes_AsString(ptr) as *const u8 };
let length = unsafe { pyo3::ffi::PyBytes_Size(ptr) as usize };
data = unsafe { String::from_utf8_lossy(std::slice::from_raw_parts(buffer, length)) };
} else {
return Err(pyo3::exceptions::TypeError::py_err(format!(
"Input must be str or bytes, not: {}",
obj_ref.get_type().name()
)));
return Err(pyo3::exceptions::TypeError::py_err(
"Input must be str or bytes",
));
}

let seed = JsonValue::new();
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ fn orjson(py: Python, m: &PyModule) -> PyResult<()> {
/// Deserialize JSON to Python objects.
#[pyfunction]
pub fn loads(py: Python, obj: PyObject) -> PyResult<PyObject> {
decode::deserialize(py, obj)
decode::deserialize(py, obj.as_ptr())
}

/// dumps(obj, /)
Expand Down

0 comments on commit 038e93b

Please sign in to comment.