forked from ijl/orjson
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault.rs
More file actions
71 lines (65 loc) · 2.03 KB
/
Copy pathdefault.rs
File metadata and controls
71 lines (65 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::*;
use crate::serialize::error::*;
use crate::serialize::serializer::*;
use serde::ser::{Serialize, Serializer};
use std::ptr::NonNull;
pub struct DefaultSerializer {
ptr: *mut pyo3_ffi::PyObject,
opts: Opt,
default_calls: u8,
recursion: u8,
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl DefaultSerializer {
pub fn new(
ptr: *mut pyo3_ffi::PyObject,
opts: Opt,
default_calls: u8,
recursion: u8,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
DefaultSerializer {
ptr: ptr,
opts: opts,
default_calls: default_calls,
recursion: recursion,
default: default,
}
}
}
impl Serialize for DefaultSerializer {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.default {
Some(callable) => {
if unlikely!(self.default_calls == RECURSION_LIMIT) {
err!(SerializeError::DefaultRecursionLimit)
}
let default_obj = ffi!(PyObject_CallFunctionObjArgs(
callable.as_ptr(),
self.ptr,
std::ptr::null_mut() as *mut pyo3_ffi::PyObject
));
if unlikely!(default_obj.is_null()) {
err!(SerializeError::UnsupportedType(nonnull!(self.ptr)))
} else {
let res = PyObjectSerializer::new(
default_obj,
self.opts,
self.default_calls + 1,
self.recursion,
self.default,
)
.serialize(serializer);
ffi!(Py_DECREF(default_obj));
res
}
}
None => err!(SerializeError::UnsupportedType(nonnull!(self.ptr))),
}
}
}