Skip to content

Commit

Permalink
refactor: split list and tuple serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
blacha committed Nov 4, 2021
1 parent c757370 commit 0ada8f3
Showing 1 changed file with 31 additions and 14 deletions.
45 changes: 31 additions & 14 deletions bindings/python/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,30 +149,47 @@ impl Serialize for SerializePyObject {
map.end()
}
}
ObjectType::Tuple | ObjectType::List => {
ObjectType::List => {
if self.recursion_depth == RECURSION_LIMIT {
return Err(ser::Error::custom("Recursion limit reached"));
}

let length = match self.object_type {
ObjectType::Tuple => unsafe { PyTuple_GET_SIZE(self.object) as usize },
ObjectType::List => unsafe { PyList_GET_SIZE(self.object) as usize },
_ => return Err(ser::Error::custom("Object is not a list or tuple")),
};
let length = unsafe { PyList_GET_SIZE(self.object) as usize };
if length == 0 {
serializer.serialize_seq(Some(0))?.end()
} else {
let mut type_ptr = std::ptr::null_mut();
let mut ob_type = ObjectType::Str;
let mut sequence = serializer.serialize_seq(Some(length))?;
for i in 0..length {
let elem = match self.object_type {
ObjectType::Tuple => unsafe {
PyTuple_GET_ITEM(self.object, i as isize)
},
ObjectType::List => unsafe { PyList_GET_ITEM(self.object, i as isize) },
_ => return Err(ser::Error::custom("Object is not a list or tuple")),
};
let elem = unsafe { PyList_GET_ITEM(self.object, i as isize) };
let current_ob_type = unsafe { Py_TYPE(elem) };
if current_ob_type != type_ptr {
type_ptr = current_ob_type;
ob_type = get_object_type(current_ob_type);
}
#[allow(clippy::integer_arithmetic)]
sequence.serialize_element(&SerializePyObject::with_obtype(
elem,
ob_type.clone(),
self.recursion_depth + 1,
))?;
}
sequence.end()
}
}
ObjectType::Tuple => {
if self.recursion_depth == RECURSION_LIMIT {
return Err(ser::Error::custom("Recursion limit reached"));
}
let length = unsafe { PyTuple_GET_SIZE(self.object) as usize };
if length == 0 {
serializer.serialize_seq(Some(0))?.end()
} else {
let mut type_ptr = std::ptr::null_mut();
let mut ob_type = ObjectType::Str;
let mut sequence = serializer.serialize_seq(Some(length))?;
for i in 0..length {
let elem = unsafe { PyTuple_GET_ITEM(self.object, i as isize) };
let current_ob_type = unsafe { Py_TYPE(elem) };
if current_ob_type != type_ptr {
type_ptr = current_ob_type;
Expand Down

0 comments on commit 0ada8f3

Please sign in to comment.