forked from ijl/orjson
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathint.rs
More file actions
90 lines (79 loc) · 2.22 KB
/
Copy pathint.rs
File metadata and controls
90 lines (79 loc) · 2.22 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::error::*;
use serde::ser::{Serialize, Serializer};
// https://tools.ietf.org/html/rfc7159#section-6
// "[-(2**53)+1, (2**53)-1]"
const STRICT_INT_MIN: i64 = -9007199254740991;
const STRICT_INT_MAX: i64 = 9007199254740991;
#[repr(transparent)]
pub struct IntSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl IntSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
IntSerializer { ptr: ptr }
}
}
impl Serialize for IntSerializer {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let val = ffi!(PyLong_AsLongLong(self.ptr));
if unlikely!(val == -1 && !ffi!(PyErr_Occurred()).is_null()) {
UIntSerializer::new(self.ptr).serialize(serializer)
} else {
serializer.serialize_i64(val)
}
}
}
#[repr(transparent)]
pub struct UIntSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl UIntSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
UIntSerializer { ptr: ptr }
}
}
impl Serialize for UIntSerializer {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
ffi!(PyErr_Clear());
let val = ffi!(PyLong_AsUnsignedLongLong(self.ptr));
if unlikely!(val == u64::MAX && !ffi!(PyErr_Occurred()).is_null()) {
err!(SerializeError::Integer64Bits)
}
serializer.serialize_u64(val)
}
}
#[repr(transparent)]
pub struct Int53Serializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl Int53Serializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
Int53Serializer { ptr: ptr }
}
}
impl Serialize for Int53Serializer {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let val = ffi!(PyLong_AsLongLong(self.ptr));
if unlikely!(val == -1 && !ffi!(PyErr_Occurred()).is_null())
|| !(STRICT_INT_MIN..=STRICT_INT_MAX).contains(&val)
{
err!(SerializeError::Integer53Bits)
}
serializer.serialize_i64(val)
}
}