index int64 0 0 | repo_id stringclasses 596 values | file_path stringlengths 31 168 | content stringlengths 1 6.2M |
|---|---|---|---|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip14.json | [-9223372036854775808] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip15.json | [1] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip17.json | [4294967295] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip07.json | {} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip27.json | [1.7976931348623157e308] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip23.json | [-1.2345] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip08.json | [0,1] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip12.json | [-2147483648] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip04.json | [0] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip01.json | [null] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip06.json | [] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip24.json | [5e-324] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip22.json | [1.2345] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip05.json | ["foo"] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip09.json | {"foo":"bar"} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip03.json | [false] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip02.json | [true] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip25.json | [2.225073858507201e-308] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip19.json | [9223372036854775807] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip18.json | [1234567890123456789] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip13.json | [-1234567890123456789] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip10.json | {"a":null,"foo":"bar"} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip11.json | [-1] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip21.json | [-0.0] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip16.json | [2147483647] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip26.json | [2.2250738585072014e-308] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/roundtrip/roundtrip20.json | [0.0] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/object_same_key_unclear_values.json | {"a":0, "a":-0}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/number_1e-999.json | [1E-999] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/number_1000000000000000.json | [1000000000000000]
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/object_key_nfd_nfc.json | {"é":"NFD","é":"NFC"} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/number_1.000000000000000005.json | [1.000000000000000005] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/number_1e6.json | [1E6] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/number_10000000000000000999.json | [10000000000000000999] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/string_2_escaped_invalid_codepoints.json | ["\uD800\uD800"] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/object_same_key_different_values.json | {"a":1,"a":2} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/string_3_escaped_invalid_codepoints.json | ["\uD800\uD800\uD800"] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/object_key_nfc_nfd.json | {"é":"NFC","é":"NFD"} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/string_1_escaped_invalid_codepoint.json | ["\uD800"] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/object_same_key_same_value.json | {"a":1,"a":1} |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/number_1.0.json | [1.0] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson/data | lc_public_repos/langsmith-sdk/vendor/orjson/data/transform/string_with_escaped_NULL.json | ["A\u0000B"] |
0 | lc_public_repos/langsmith-sdk/vendor/orjson | lc_public_repos/langsmith-sdk/vendor/orjson/src/opt.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
pub type Opt = u32;
pub const INDENT_2: Opt = 1;
pub const NAIVE_UTC: Opt = 1 << 1;
pub const NON_STR_KEYS: Opt = 1 << 2;
pub const OMIT_MICROSECONDS: Opt = 1 << 3;
pub const SERIALIZE_NUMPY: Opt = 1 << 4;
pub const SORT_KEYS: Opt = 1 << 5;
pub const STRICT_INTEGER: Opt = 1 << 6;
pub const UTC_Z: Opt = 1 << 7;
pub const PASSTHROUGH_SUBCLASS: Opt = 1 << 8;
pub const PASSTHROUGH_DATETIME: Opt = 1 << 9;
pub const APPEND_NEWLINE: Opt = 1 << 10;
pub const PASSTHROUGH_DATACLASS: Opt = 1 << 11;
// deprecated
pub const SERIALIZE_DATACLASS: Opt = 0;
pub const SERIALIZE_UUID: Opt = 0;
pub const SORT_OR_NON_STR_KEYS: Opt = SORT_KEYS | NON_STR_KEYS;
pub const NOT_PASSTHROUGH: Opt =
!(PASSTHROUGH_DATETIME | PASSTHROUGH_DATACLASS | PASSTHROUGH_SUBCLASS);
pub const MAX_OPT: i32 = (APPEND_NEWLINE
| INDENT_2
| NAIVE_UTC
| NON_STR_KEYS
| OMIT_MICROSECONDS
| PASSTHROUGH_DATETIME
| PASSTHROUGH_DATACLASS
| PASSTHROUGH_SUBCLASS
| SERIALIZE_DATACLASS
| SERIALIZE_NUMPY
| SERIALIZE_UUID
| SORT_KEYS
| STRICT_INTEGER
| UTC_Z) as i32;
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson | lc_public_repos/langsmith-sdk/vendor/orjson/src/util.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
pub const INVALID_STR: &str = "str is not valid UTF-8: surrogates not allowed";
macro_rules! is_type {
($obj_ptr:expr, $type_ptr:expr) => {
unsafe { $obj_ptr == $type_ptr }
};
}
macro_rules! ob_type {
($obj:expr) => {
unsafe { (*$obj).ob_type }
};
}
macro_rules! is_class_by_type {
($ob_type:expr, $type_ptr:ident) => {
unsafe { $ob_type == $type_ptr }
};
}
macro_rules! is_subclass_by_flag {
($ob_type:expr, $flag:ident) => {
unsafe { (((*$ob_type).tp_flags & pyo3_ffi::$flag) != 0) }
};
}
macro_rules! is_subclass_by_type {
($ob_type:expr, $type:ident) => {
unsafe {
(*($ob_type as *mut pyo3_ffi::PyTypeObject))
.ob_base
.ob_base
.ob_type
== $type
}
};
}
macro_rules! err {
($msg:expr) => {
return Err(serde::ser::Error::custom($msg))
};
}
macro_rules! opt_enabled {
($var:expr, $flag:expr) => {
$var & $flag != 0
};
}
macro_rules! opt_disabled {
($var:expr, $flag:expr) => {
$var & $flag == 0
};
}
#[cfg(feature = "intrinsics")]
macro_rules! unlikely {
($exp:expr) => {
core::intrinsics::unlikely($exp)
};
}
#[cfg(not(feature = "intrinsics"))]
macro_rules! unlikely {
($exp:expr) => {
$exp
};
}
#[allow(unused_macros)]
#[cfg(feature = "intrinsics")]
macro_rules! likely {
($exp:expr) => {
core::intrinsics::likely($exp)
};
}
#[allow(unused_macros)]
#[cfg(not(feature = "intrinsics"))]
macro_rules! likely {
($exp:expr) => {
$exp
};
}
macro_rules! nonnull {
($exp:expr) => {
unsafe { core::ptr::NonNull::new_unchecked($exp) }
};
}
macro_rules! str_from_slice {
($ptr:expr, $size:expr) => {
unsafe { std::str::from_utf8_unchecked(core::slice::from_raw_parts($ptr, $size as usize)) }
};
}
#[cfg(Py_3_12)]
macro_rules! reverse_pydict_incref {
($op:expr) => {
unsafe {
if pyo3_ffi::_Py_IsImmortal($op) == 0 {
debug_assert!(ffi!(Py_REFCNT($op)) >= 2);
(*$op).ob_refcnt.ob_refcnt -= 1;
}
}
};
}
#[cfg(not(Py_3_12))]
macro_rules! reverse_pydict_incref {
($op:expr) => {
unsafe {
debug_assert!(ffi!(Py_REFCNT($op)) >= 2);
(*$op).ob_refcnt -= 1;
}
};
}
macro_rules! ffi {
($fn:ident()) => {
unsafe { pyo3_ffi::$fn() }
};
($fn:ident($obj1:expr)) => {
unsafe { pyo3_ffi::$fn($obj1) }
};
($fn:ident($obj1:expr, $obj2:expr)) => {
unsafe { pyo3_ffi::$fn($obj1, $obj2) }
};
($fn:ident($obj1:expr, $obj2:expr, $obj3:expr)) => {
unsafe { pyo3_ffi::$fn($obj1, $obj2, $obj3) }
};
($fn:ident($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr)) => {
unsafe { pyo3_ffi::$fn($obj1, $obj2, $obj3, $obj4) }
};
}
#[cfg(Py_3_9)]
macro_rules! call_method {
($obj1:expr, $obj2:expr) => {
unsafe { pyo3_ffi::PyObject_CallMethodNoArgs($obj1, $obj2) }
};
($obj1:expr, $obj2:expr, $obj3:expr) => {
unsafe { pyo3_ffi::PyObject_CallMethodOneArg($obj1, $obj2, $obj3) }
};
}
#[cfg(not(Py_3_9))]
macro_rules! call_method {
($obj1:expr, $obj2:expr) => {
unsafe {
pyo3_ffi::PyObject_CallMethodObjArgs(
$obj1,
$obj2,
core::ptr::null_mut() as *mut pyo3_ffi::PyObject,
)
}
};
($obj1:expr, $obj2:expr, $obj3:expr) => {
unsafe {
pyo3_ffi::PyObject_CallMethodObjArgs(
$obj1,
$obj2,
$obj3,
core::ptr::null_mut() as *mut pyo3_ffi::PyObject,
)
}
};
}
macro_rules! str_hash {
($op:expr) => {
unsafe { (*$op.cast::<pyo3_ffi::PyASCIIObject>()).hash }
};
}
#[cfg(Py_3_13)]
macro_rules! pydict_contains {
($obj1:expr, $obj2:expr) => {
unsafe { pyo3_ffi::PyDict_Contains(pyo3_ffi::PyType_GetDict($obj1), $obj2) == 1 }
};
}
#[cfg(all(Py_3_12, not(Py_3_13)))]
macro_rules! pydict_contains {
($obj1:expr, $obj2:expr) => {
unsafe {
pyo3_ffi::_PyDict_Contains_KnownHash(
pyo3_ffi::PyType_GetDict($obj1),
$obj2,
(*$obj2.cast::<pyo3_ffi::PyASCIIObject>()).hash,
) == 1
}
};
}
#[cfg(all(Py_3_10, not(Py_3_12)))]
macro_rules! pydict_contains {
($obj1:expr, $obj2:expr) => {
unsafe {
pyo3_ffi::_PyDict_Contains_KnownHash(
(*$obj1).tp_dict,
$obj2,
(*$obj2.cast::<pyo3_ffi::PyASCIIObject>()).hash,
) == 1
}
};
}
#[cfg(not(Py_3_10))]
macro_rules! pydict_contains {
($obj1:expr, $obj2:expr) => {
unsafe { pyo3_ffi::PyDict_Contains((*$obj1).tp_dict, $obj2) == 1 }
};
}
#[cfg(Py_3_12)]
macro_rules! use_immortal {
($op:expr) => {
unsafe { $op }
};
}
#[cfg(not(Py_3_12))]
macro_rules! use_immortal {
($op:expr) => {
unsafe {
ffi!(Py_INCREF($op));
$op
}
};
}
#[cfg(not(Py_3_13))]
macro_rules! pydict_next {
($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr) => {
unsafe { pyo3_ffi::_PyDict_Next($obj1, $obj2, $obj3, $obj4, core::ptr::null_mut()) }
};
}
#[cfg(Py_3_13)]
macro_rules! pydict_next {
($obj1:expr, $obj2:expr, $obj3:expr, $obj4:expr) => {
unsafe { pyo3_ffi::PyDict_Next($obj1, $obj2, $obj3, $obj4) }
};
}
macro_rules! reserve_minimum {
($writer:expr) => {
$writer.reserve(64);
};
}
macro_rules! reserve_pretty {
($writer:expr, $val:expr) => {
$writer.reserve($val + 16);
};
}
macro_rules! assume {
($expr:expr) => {
debug_assert!($expr);
#[cfg(feature = "intrinsics")]
unsafe {
core::intrinsics::assume($expr);
};
};
}
#[allow(unused_macros)]
#[cfg(feature = "intrinsics")]
macro_rules! trailing_zeros {
($val:expr) => {
core::intrinsics::cttz_nonzero($val) as usize
};
}
#[allow(unused_macros)]
#[cfg(not(feature = "intrinsics"))]
macro_rules! trailing_zeros {
($val:expr) => {
$val.trailing_zeros() as usize
};
}
#[allow(unused_macros)]
#[cfg(feature = "intrinsics")]
macro_rules! popcnt {
($val:expr) => {
core::intrinsics::ctpop(core::mem::transmute::<u32, i32>($val)) as usize
};
}
#[allow(unused_macros)]
#[cfg(not(feature = "intrinsics"))]
macro_rules! popcnt {
($val:expr) => {
core::mem::transmute::<u32, i32>($val).count_ones() as usize
};
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson | lc_public_repos/langsmith-sdk/vendor/orjson/src/lib.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
#![cfg_attr(feature = "avx512", feature(stdarch_x86_avx512, avx512_target_feature))]
#![cfg_attr(feature = "intrinsics", feature(core_intrinsics))]
#![cfg_attr(feature = "optimize", feature(optimize_attribute))]
#![cfg_attr(feature = "unstable-simd", feature(portable_simd))]
#![allow(internal_features)] // core_intrinsics
#![allow(non_camel_case_types)]
#![allow(static_mut_refs)]
#![allow(unknown_lints)] // internal_features
#![allow(unused_unsafe)]
#![allow(clippy::missing_safety_doc)]
#![allow(clippy::redundant_field_names)]
#![allow(clippy::uninlined_format_args)] // MSRV 1.66
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::zero_prefixed_literal)]
#[cfg(feature = "unwind")]
extern crate unwinding;
#[macro_use]
mod util;
mod deserialize;
mod ffi;
mod opt;
mod serialize;
mod str;
mod typeref;
pub use typeref::init_typerefs;
pub use serialize::{to_writer, WriteExt, PyObjectSerializer, SerializerState};
use core::ffi::{c_char, c_int, c_void};
use pyo3_ffi::*;
#[allow(unused_imports)]
use core::ptr::{null, null_mut, NonNull};
#[cfg(Py_3_13)]
macro_rules! add {
($mptr:expr, $name:expr, $obj:expr) => {
PyModule_Add($mptr, $name.as_ptr() as *const c_char, $obj);
};
}
#[cfg(all(Py_3_10, not(Py_3_13)))]
macro_rules! add {
($mptr:expr, $name:expr, $obj:expr) => {
PyModule_AddObjectRef($mptr, $name.as_ptr() as *const c_char, $obj);
};
}
#[cfg(not(Py_3_10))]
macro_rules! add {
($mptr:expr, $name:expr, $obj:expr) => {
PyModule_AddObject($mptr, $name.as_ptr() as *const c_char, $obj);
};
}
macro_rules! opt {
($mptr:expr, $name:expr, $opt:expr) => {
#[cfg(all(not(target_os = "windows"), target_pointer_width = "64"))]
PyModule_AddIntConstant($mptr, $name.as_ptr() as *const c_char, $opt as i64);
#[cfg(all(not(target_os = "windows"), target_pointer_width = "32"))]
PyModule_AddIntConstant($mptr, $name.as_ptr() as *const c_char, $opt as i32);
#[cfg(target_os = "windows")]
PyModule_AddIntConstant($mptr, $name.as_ptr() as *const c_char, $opt as i32);
};
}
#[allow(non_snake_case)]
#[no_mangle]
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub unsafe extern "C" fn orjson_init_exec(mptr: *mut PyObject) -> c_int {
typeref::init_typerefs();
{
let version = env!("CARGO_PKG_VERSION");
let pyversion =
PyUnicode_FromStringAndSize(version.as_ptr() as *const c_char, version.len() as isize);
add!(mptr, "__version__\0", pyversion);
}
{
let dumps_doc =
"dumps(obj, /, default=None, option=None)\n--\n\nSerialize Python objects to JSON.\0";
let wrapped_dumps = PyMethodDef {
ml_name: "dumps\0".as_ptr() as *const c_char,
ml_meth: PyMethodDefPointer {
#[cfg(Py_3_10)]
PyCFunctionFastWithKeywords: dumps,
#[cfg(not(Py_3_10))]
_PyCFunctionFastWithKeywords: dumps,
},
ml_flags: pyo3_ffi::METH_FASTCALL | METH_KEYWORDS,
ml_doc: dumps_doc.as_ptr() as *const c_char,
};
let func = PyCFunction_NewEx(
Box::into_raw(Box::new(wrapped_dumps)),
null_mut(),
PyUnicode_InternFromString("orjson\0".as_ptr() as *const c_char),
);
add!(mptr, "dumps\0", func);
}
{
let loads_doc = "loads(obj, /)\n--\n\nDeserialize JSON to Python objects.\0";
let wrapped_loads = PyMethodDef {
ml_name: "loads\0".as_ptr() as *const c_char,
ml_meth: PyMethodDefPointer { PyCFunction: loads },
ml_flags: METH_O,
ml_doc: loads_doc.as_ptr() as *const c_char,
};
let func = PyCFunction_NewEx(
Box::into_raw(Box::new(wrapped_loads)),
null_mut(),
PyUnicode_InternFromString("orjson\0".as_ptr() as *const c_char),
);
add!(mptr, "loads\0", func);
}
add!(mptr, "Fragment\0", typeref::FRAGMENT_TYPE as *mut PyObject);
opt!(mptr, "OPT_APPEND_NEWLINE\0", opt::APPEND_NEWLINE);
opt!(mptr, "OPT_INDENT_2\0", opt::INDENT_2);
opt!(mptr, "OPT_NAIVE_UTC\0", opt::NAIVE_UTC);
opt!(mptr, "OPT_NON_STR_KEYS\0", opt::NON_STR_KEYS);
opt!(mptr, "OPT_OMIT_MICROSECONDS\0", opt::OMIT_MICROSECONDS);
opt!(
mptr,
"OPT_PASSTHROUGH_DATACLASS\0",
opt::PASSTHROUGH_DATACLASS
);
opt!(
mptr,
"OPT_PASSTHROUGH_DATETIME\0",
opt::PASSTHROUGH_DATETIME
);
opt!(
mptr,
"OPT_PASSTHROUGH_SUBCLASS\0",
opt::PASSTHROUGH_SUBCLASS
);
opt!(mptr, "OPT_SERIALIZE_DATACLASS\0", opt::SERIALIZE_DATACLASS);
opt!(mptr, "OPT_SERIALIZE_NUMPY\0", opt::SERIALIZE_NUMPY);
opt!(mptr, "OPT_SERIALIZE_UUID\0", opt::SERIALIZE_UUID);
opt!(mptr, "OPT_SORT_KEYS\0", opt::SORT_KEYS);
opt!(mptr, "OPT_STRICT_INTEGER\0", opt::STRICT_INTEGER);
opt!(mptr, "OPT_UTC_Z\0", opt::UTC_Z);
add!(mptr, "JSONDecodeError\0", typeref::JsonDecodeError);
add!(mptr, "JSONEncodeError\0", typeref::JsonEncodeError);
0
}
#[cfg(Py_3_13)]
#[allow(non_upper_case_globals)]
const Py_mod_gil: c_int = 4;
#[cfg(Py_3_13)]
#[allow(non_upper_case_globals, dead_code, fuzzy_provenance_casts)]
const Py_MOD_GIL_USED: *mut c_void = 0 as *mut c_void;
#[cfg(Py_3_13)]
#[allow(non_upper_case_globals, dead_code, fuzzy_provenance_casts)]
const Py_MOD_GIL_NOT_USED: *mut c_void = 1 as *mut c_void;
#[cfg(not(Py_3_12))]
const PYMODULEDEF_LEN: usize = 2;
#[cfg(all(Py_3_12, not(Py_3_13)))]
const PYMODULEDEF_LEN: usize = 3;
#[cfg(Py_3_13)]
const PYMODULEDEF_LEN: usize = 4;
#[allow(non_snake_case)]
#[no_mangle]
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub unsafe extern "C" fn PyInit_orjson() -> *mut PyModuleDef {
let mod_slots: Box<[PyModuleDef_Slot; PYMODULEDEF_LEN]> = Box::new([
PyModuleDef_Slot {
slot: Py_mod_exec,
value: orjson_init_exec as *mut c_void,
},
#[cfg(Py_3_12)]
PyModuleDef_Slot {
slot: Py_mod_multiple_interpreters,
value: Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED,
},
#[cfg(Py_3_13)]
PyModuleDef_Slot {
slot: Py_mod_gil,
value: Py_MOD_GIL_USED,
},
PyModuleDef_Slot {
slot: 0,
value: null_mut(),
},
]);
let init = Box::new(PyModuleDef {
m_base: PyModuleDef_HEAD_INIT,
m_name: "orjson\0".as_ptr() as *const c_char,
m_doc: null(),
m_size: 0,
m_methods: null_mut(),
m_slots: Box::into_raw(mod_slots) as *mut PyModuleDef_Slot,
m_traverse: None,
m_clear: None,
m_free: None,
});
let init_ptr = Box::into_raw(init);
PyModuleDef_Init(init_ptr);
init_ptr
}
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn raise_loads_exception(err: deserialize::DeserializeError) -> *mut PyObject {
let pos = err.pos();
let msg = err.message;
let doc = match err.data {
Some(as_str) => unsafe {
PyUnicode_FromStringAndSize(as_str.as_ptr() as *const c_char, as_str.len() as isize)
},
None => {
use_immortal!(crate::typeref::EMPTY_UNICODE)
}
};
unsafe {
let err_msg =
PyUnicode_FromStringAndSize(msg.as_ptr() as *const c_char, msg.len() as isize);
let args = PyTuple_New(3);
let pos = PyLong_FromLongLong(pos);
PyTuple_SET_ITEM(args, 0, err_msg);
PyTuple_SET_ITEM(args, 1, doc);
PyTuple_SET_ITEM(args, 2, pos);
PyErr_SetObject(typeref::JsonDecodeError, args);
debug_assert!(ffi!(Py_REFCNT(args)) <= 2);
Py_DECREF(args);
};
null_mut()
}
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn raise_dumps_exception_fixed(msg: &str) -> *mut PyObject {
unsafe {
let err_msg =
PyUnicode_FromStringAndSize(msg.as_ptr() as *const c_char, msg.len() as isize);
PyErr_SetObject(typeref::JsonEncodeError, err_msg);
debug_assert!(ffi!(Py_REFCNT(err_msg)) <= 2);
Py_DECREF(err_msg);
};
null_mut()
}
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
#[cfg(Py_3_12)]
fn raise_dumps_exception_dynamic(err: &str) -> *mut PyObject {
unsafe {
let cause_exc: *mut PyObject = PyErr_GetRaisedException();
let err_msg =
PyUnicode_FromStringAndSize(err.as_ptr() as *const c_char, err.len() as isize);
PyErr_SetObject(typeref::JsonEncodeError, err_msg);
debug_assert!(ffi!(Py_REFCNT(err_msg)) <= 2);
Py_DECREF(err_msg);
if !cause_exc.is_null() {
let exc: *mut PyObject = PyErr_GetRaisedException();
PyException_SetCause(exc, cause_exc);
PyErr_SetRaisedException(exc);
}
};
null_mut()
}
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
#[cfg(not(Py_3_12))]
fn raise_dumps_exception_dynamic(err: &str) -> *mut PyObject {
unsafe {
let mut cause_tp: *mut PyObject = null_mut();
let mut cause_val: *mut PyObject = null_mut();
let mut cause_traceback: *mut PyObject = null_mut();
PyErr_Fetch(&mut cause_tp, &mut cause_val, &mut cause_traceback);
let err_msg =
PyUnicode_FromStringAndSize(err.as_ptr() as *const c_char, err.len() as isize);
PyErr_SetObject(typeref::JsonEncodeError, err_msg);
debug_assert!(ffi!(Py_REFCNT(err_msg)) == 2);
Py_DECREF(err_msg);
let mut tp: *mut PyObject = null_mut();
let mut val: *mut PyObject = null_mut();
let mut traceback: *mut PyObject = null_mut();
PyErr_Fetch(&mut tp, &mut val, &mut traceback);
PyErr_NormalizeException(&mut tp, &mut val, &mut traceback);
if !cause_tp.is_null() {
PyErr_NormalizeException(&mut cause_tp, &mut cause_val, &mut cause_traceback);
PyException_SetCause(val, cause_val);
Py_DECREF(cause_tp);
}
if !cause_traceback.is_null() {
Py_DECREF(cause_traceback);
}
PyErr_Restore(tp, val, traceback);
};
null_mut()
}
#[no_mangle]
pub unsafe extern "C" fn loads(_self: *mut PyObject, obj: *mut PyObject) -> *mut PyObject {
match crate::deserialize::deserialize(obj) {
Ok(val) => val.as_ptr(),
Err(err) => raise_loads_exception(err),
}
}
#[no_mangle]
pub unsafe extern "C" fn dumps(
_self: *mut PyObject,
args: *const *mut PyObject,
nargs: Py_ssize_t,
kwnames: *mut PyObject,
) -> *mut PyObject {
let mut default: Option<NonNull<PyObject>> = None;
let mut optsptr: Option<NonNull<PyObject>> = None;
let num_args = PyVectorcall_NARGS(nargs as usize);
if unlikely!(num_args == 0) {
return raise_dumps_exception_fixed(
"dumps() missing 1 required positional argument: 'obj'",
);
}
if num_args & 2 == 2 {
default = Some(NonNull::new_unchecked(*args.offset(1)));
}
if num_args & 3 == 3 {
optsptr = Some(NonNull::new_unchecked(*args.offset(2)));
}
if unlikely!(!kwnames.is_null()) {
for i in 0..=Py_SIZE(kwnames).saturating_sub(1) {
let arg = PyTuple_GET_ITEM(kwnames, i as Py_ssize_t);
if arg == typeref::DEFAULT {
if unlikely!(num_args & 2 == 2) {
return raise_dumps_exception_fixed(
"dumps() got multiple values for argument: 'default'",
);
}
default = Some(NonNull::new_unchecked(*args.offset(num_args + i)));
} else if arg == typeref::OPTION {
if unlikely!(num_args & 3 == 3) {
return raise_dumps_exception_fixed(
"dumps() got multiple values for argument: 'option'",
);
}
optsptr = Some(NonNull::new_unchecked(*args.offset(num_args + i)));
} else {
return raise_dumps_exception_fixed("dumps() got an unexpected keyword argument");
}
}
}
let mut optsbits: i32 = 0;
if unlikely!(optsptr.is_some()) {
let opts = optsptr.unwrap();
if (*opts.as_ptr()).ob_type == typeref::INT_TYPE {
optsbits = PyLong_AsLong(optsptr.unwrap().as_ptr()) as i32;
if unlikely!(!(0..=opt::MAX_OPT).contains(&optsbits)) {
return raise_dumps_exception_fixed("Invalid opts");
}
} else if unlikely!(opts.as_ptr() != typeref::NONE) {
return raise_dumps_exception_fixed("Invalid opts");
}
}
match crate::serialize::serialize(*args, default, optsbits as opt::Opt) {
Ok(val) => val.as_ptr(),
Err(err) => raise_dumps_exception_dynamic(err.as_str()),
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson | lc_public_repos/langsmith-sdk/vendor/orjson/src/typeref.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::ffi::orjson_fragmenttype_new;
use core::ffi::c_char;
#[cfg(feature = "yyjson")]
use core::ffi::c_void;
#[cfg(feature = "yyjson")]
use core::mem::MaybeUninit;
use core::ptr::{null_mut, NonNull};
use once_cell::race::{OnceBool, OnceBox};
use pyo3_ffi::*;
#[cfg(feature = "yyjson")]
use std::cell::UnsafeCell;
pub struct NumpyTypes {
pub array: *mut PyTypeObject,
pub float64: *mut PyTypeObject,
pub float32: *mut PyTypeObject,
pub float16: *mut PyTypeObject,
pub int64: *mut PyTypeObject,
pub int32: *mut PyTypeObject,
pub int16: *mut PyTypeObject,
pub int8: *mut PyTypeObject,
pub uint64: *mut PyTypeObject,
pub uint32: *mut PyTypeObject,
pub uint16: *mut PyTypeObject,
pub uint8: *mut PyTypeObject,
pub bool_: *mut PyTypeObject,
pub datetime64: *mut PyTypeObject,
}
pub static mut DEFAULT: *mut PyObject = null_mut();
pub static mut OPTION: *mut PyObject = null_mut();
pub static mut NONE: *mut PyObject = null_mut();
pub static mut TRUE: *mut PyObject = null_mut();
pub static mut FALSE: *mut PyObject = null_mut();
pub static mut EMPTY_UNICODE: *mut PyObject = null_mut();
pub static mut BYTES_TYPE: *mut PyTypeObject = null_mut();
pub static mut BYTEARRAY_TYPE: *mut PyTypeObject = null_mut();
pub static mut MEMORYVIEW_TYPE: *mut PyTypeObject = null_mut();
pub static mut STR_TYPE: *mut PyTypeObject = null_mut();
pub static mut INT_TYPE: *mut PyTypeObject = null_mut();
pub static mut BOOL_TYPE: *mut PyTypeObject = null_mut();
pub static mut NONE_TYPE: *mut PyTypeObject = null_mut();
pub static mut FLOAT_TYPE: *mut PyTypeObject = null_mut();
pub static mut LIST_TYPE: *mut PyTypeObject = null_mut();
pub static mut DICT_TYPE: *mut PyTypeObject = null_mut();
pub static mut DATETIME_TYPE: *mut PyTypeObject = null_mut();
pub static mut DATE_TYPE: *mut PyTypeObject = null_mut();
pub static mut TIME_TYPE: *mut PyTypeObject = null_mut();
pub static mut TUPLE_TYPE: *mut PyTypeObject = null_mut();
pub static mut UUID_TYPE: *mut PyTypeObject = null_mut();
pub static mut ENUM_TYPE: *mut PyTypeObject = null_mut();
pub static mut FIELD_TYPE: *mut PyTypeObject = null_mut();
pub static mut FRAGMENT_TYPE: *mut PyTypeObject = null_mut();
pub static mut NUMPY_TYPES: OnceBox<Option<NonNull<NumpyTypes>>> = OnceBox::new();
#[cfg(Py_3_9)]
pub static mut ZONEINFO_TYPE: *mut PyTypeObject = null_mut();
pub static mut UTCOFFSET_METHOD_STR: *mut PyObject = null_mut();
pub static mut NORMALIZE_METHOD_STR: *mut PyObject = null_mut();
pub static mut CONVERT_METHOD_STR: *mut PyObject = null_mut();
pub static mut DST_STR: *mut PyObject = null_mut();
pub static mut DICT_STR: *mut PyObject = null_mut();
pub static mut DATACLASS_FIELDS_STR: *mut PyObject = null_mut();
pub static mut SLOTS_STR: *mut PyObject = null_mut();
pub static mut FIELD_TYPE_STR: *mut PyObject = null_mut();
pub static mut ARRAY_STRUCT_STR: *mut PyObject = null_mut();
pub static mut DTYPE_STR: *mut PyObject = null_mut();
pub static mut DESCR_STR: *mut PyObject = null_mut();
pub static mut VALUE_STR: *mut PyObject = null_mut();
pub static mut INT_ATTR_STR: *mut PyObject = null_mut();
#[cfg(feature = "yyjson")]
pub const YYJSON_BUFFER_SIZE: usize = 1024 * 1024 * 8;
#[cfg(feature = "yyjson")]
#[repr(align(64))]
struct YYJSONBuffer(UnsafeCell<MaybeUninit<[u8; YYJSON_BUFFER_SIZE]>>);
#[cfg(feature = "yyjson")]
pub struct YYJSONAlloc {
pub alloc: crate::ffi::yyjson::yyjson_alc,
_buffer: Box<YYJSONBuffer>,
}
#[cfg(feature = "yyjson")]
pub static mut YYJSON_ALLOC: OnceBox<YYJSONAlloc> = OnceBox::new();
#[cfg(feature = "yyjson")]
pub fn yyjson_init() -> Box<YYJSONAlloc> {
// Using unsafe to ensure allocation happens on the heap without going through the stack
// so we don't stack overflow in debug mode. Once rust-lang/rust#63291 is stable (Box::new_uninit)
// we can use that instead.
let layout = std::alloc::Layout::new::<YYJSONBuffer>();
let buffer = unsafe { Box::from_raw(std::alloc::alloc(layout).cast::<YYJSONBuffer>()) };
let mut alloc = crate::ffi::yyjson::yyjson_alc {
malloc: None,
realloc: None,
free: None,
ctx: null_mut(),
};
unsafe {
crate::ffi::yyjson::yyjson_alc_pool_init(
&mut alloc,
buffer.0.get().cast::<c_void>(),
YYJSON_BUFFER_SIZE,
);
}
Box::new(YYJSONAlloc {
alloc,
_buffer: buffer,
})
}
#[allow(non_upper_case_globals)]
pub static mut JsonEncodeError: *mut PyObject = null_mut();
#[allow(non_upper_case_globals)]
pub static mut JsonDecodeError: *mut PyObject = null_mut();
static INIT: OnceBool = OnceBool::new();
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub fn init_typerefs() {
INIT.get_or_init(_init_typerefs_impl);
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
fn _init_typerefs_impl() -> bool {
unsafe {
debug_assert!(crate::opt::MAX_OPT < u16::MAX as i32);
assert!(crate::deserialize::KEY_MAP
.set(crate::deserialize::KeyMap::default())
.is_ok());
FRAGMENT_TYPE = orjson_fragmenttype_new();
PyDateTime_IMPORT();
NONE = Py_None();
TRUE = Py_True();
FALSE = Py_False();
EMPTY_UNICODE = PyUnicode_New(0, 255);
STR_TYPE = (*EMPTY_UNICODE).ob_type;
BYTES_TYPE = (*PyBytes_FromStringAndSize("".as_ptr() as *const c_char, 0)).ob_type;
{
let bytearray = PyByteArray_FromStringAndSize("".as_ptr() as *const c_char, 0);
BYTEARRAY_TYPE = (*bytearray).ob_type;
let memoryview = PyMemoryView_FromObject(bytearray);
MEMORYVIEW_TYPE = (*memoryview).ob_type;
Py_DECREF(memoryview);
Py_DECREF(bytearray);
}
DICT_TYPE = (*PyDict_New()).ob_type;
LIST_TYPE = (*PyList_New(0)).ob_type;
TUPLE_TYPE = (*PyTuple_New(0)).ob_type;
NONE_TYPE = (*NONE).ob_type;
BOOL_TYPE = (*TRUE).ob_type;
INT_TYPE = (*PyLong_FromLongLong(0)).ob_type;
FLOAT_TYPE = (*PyFloat_FromDouble(0.0)).ob_type;
DATETIME_TYPE = look_up_datetime_type();
DATE_TYPE = look_up_date_type();
TIME_TYPE = look_up_time_type();
UUID_TYPE = look_up_uuid_type();
ENUM_TYPE = look_up_enum_type();
FIELD_TYPE = look_up_field_type();
#[cfg(Py_3_9)]
{
ZONEINFO_TYPE = look_up_zoneinfo_type();
}
INT_ATTR_STR = PyUnicode_InternFromString("int\0".as_ptr() as *const c_char);
UTCOFFSET_METHOD_STR = PyUnicode_InternFromString("utcoffset\0".as_ptr() as *const c_char);
NORMALIZE_METHOD_STR = PyUnicode_InternFromString("normalize\0".as_ptr() as *const c_char);
CONVERT_METHOD_STR = PyUnicode_InternFromString("convert\0".as_ptr() as *const c_char);
DST_STR = PyUnicode_InternFromString("dst\0".as_ptr() as *const c_char);
DICT_STR = PyUnicode_InternFromString("__dict__\0".as_ptr() as *const c_char);
DATACLASS_FIELDS_STR =
PyUnicode_InternFromString("__dataclass_fields__\0".as_ptr() as *const c_char);
SLOTS_STR = PyUnicode_InternFromString("__slots__\0".as_ptr() as *const c_char);
FIELD_TYPE_STR = PyUnicode_InternFromString("_field_type\0".as_ptr() as *const c_char);
ARRAY_STRUCT_STR =
PyUnicode_InternFromString("__array_struct__\0".as_ptr() as *const c_char);
DTYPE_STR = PyUnicode_InternFromString("dtype\0".as_ptr() as *const c_char);
DESCR_STR = PyUnicode_InternFromString("descr\0".as_ptr() as *const c_char);
VALUE_STR = PyUnicode_InternFromString("value\0".as_ptr() as *const c_char);
DEFAULT = PyUnicode_InternFromString("default\0".as_ptr() as *const c_char);
OPTION = PyUnicode_InternFromString("option\0".as_ptr() as *const c_char);
JsonEncodeError = pyo3_ffi::PyExc_TypeError;
Py_INCREF(JsonEncodeError);
JsonDecodeError = look_up_json_exc();
};
true
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_json_exc() -> *mut PyObject {
let module = PyImport_ImportModule("json\0".as_ptr() as *const c_char);
let module_dict = PyObject_GenericGetDict(module, null_mut());
let ptr = PyMapping_GetItemString(module_dict, "JSONDecodeError\0".as_ptr() as *const c_char);
let res = pyo3_ffi::PyErr_NewException(
"orjson.JSONDecodeError\0".as_ptr() as *const c_char,
ptr,
null_mut(),
);
Py_DECREF(ptr);
Py_DECREF(module_dict);
Py_DECREF(module);
Py_INCREF(res);
res
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_numpy_type(numpy_module_dict: *mut PyObject, np_type: &str) -> *mut PyTypeObject {
let ptr = PyMapping_GetItemString(numpy_module_dict, np_type.as_ptr() as *const c_char);
Py_XDECREF(ptr);
ptr as *mut PyTypeObject
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub fn load_numpy_types() -> Box<Option<NonNull<NumpyTypes>>> {
unsafe {
let numpy = PyImport_ImportModule("numpy\0".as_ptr() as *const c_char);
if numpy.is_null() {
PyErr_Clear();
return Box::new(None);
}
let numpy_module_dict = PyObject_GenericGetDict(numpy, null_mut());
let types = Box::new(NumpyTypes {
array: look_up_numpy_type(numpy_module_dict, "ndarray\0"),
float16: look_up_numpy_type(numpy_module_dict, "half\0"),
float32: look_up_numpy_type(numpy_module_dict, "float32\0"),
float64: look_up_numpy_type(numpy_module_dict, "float64\0"),
int8: look_up_numpy_type(numpy_module_dict, "int8\0"),
int16: look_up_numpy_type(numpy_module_dict, "int16\0"),
int32: look_up_numpy_type(numpy_module_dict, "int32\0"),
int64: look_up_numpy_type(numpy_module_dict, "int64\0"),
uint16: look_up_numpy_type(numpy_module_dict, "uint16\0"),
uint32: look_up_numpy_type(numpy_module_dict, "uint32\0"),
uint64: look_up_numpy_type(numpy_module_dict, "uint64\0"),
uint8: look_up_numpy_type(numpy_module_dict, "uint8\0"),
bool_: look_up_numpy_type(numpy_module_dict, "bool_\0"),
datetime64: look_up_numpy_type(numpy_module_dict, "datetime64\0"),
});
Py_XDECREF(numpy_module_dict);
Py_XDECREF(numpy);
Box::new(Some(nonnull!(Box::<NumpyTypes>::into_raw(types))))
}
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_field_type() -> *mut PyTypeObject {
let module = PyImport_ImportModule("dataclasses\0".as_ptr() as *const c_char);
let module_dict = PyObject_GenericGetDict(module, null_mut());
let ptr = PyMapping_GetItemString(module_dict, "_FIELD\0".as_ptr() as *const c_char)
as *mut PyTypeObject;
Py_DECREF(module_dict);
Py_DECREF(module);
ptr
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_enum_type() -> *mut PyTypeObject {
let module = PyImport_ImportModule("enum\0".as_ptr() as *const c_char);
let module_dict = PyObject_GenericGetDict(module, null_mut());
let ptr = PyMapping_GetItemString(module_dict, "EnumMeta\0".as_ptr() as *const c_char)
as *mut PyTypeObject;
Py_DECREF(module_dict);
Py_DECREF(module);
ptr
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_uuid_type() -> *mut PyTypeObject {
let uuid_mod = PyImport_ImportModule("uuid\0".as_ptr() as *const c_char);
let uuid_mod_dict = PyObject_GenericGetDict(uuid_mod, null_mut());
let uuid = PyMapping_GetItemString(uuid_mod_dict, "NAMESPACE_DNS\0".as_ptr() as *const c_char);
let ptr = (*uuid).ob_type;
Py_DECREF(uuid);
Py_DECREF(uuid_mod_dict);
Py_DECREF(uuid_mod);
ptr
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_datetime_type() -> *mut PyTypeObject {
let datetime = ((*PyDateTimeAPI()).DateTime_FromDateAndTime)(
1970,
1,
1,
0,
0,
0,
0,
NONE,
(*(PyDateTimeAPI())).DateTimeType,
);
let ptr = (*datetime).ob_type;
Py_DECREF(datetime);
ptr
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_date_type() -> *mut PyTypeObject {
let date = ((*PyDateTimeAPI()).Date_FromDate)(1, 1, 1, (*(PyDateTimeAPI())).DateType);
let ptr = (*date).ob_type;
Py_DECREF(date);
ptr
}
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_time_type() -> *mut PyTypeObject {
let time = ((*PyDateTimeAPI()).Time_FromTime)(0, 0, 0, 0, NONE, (*(PyDateTimeAPI())).TimeType);
let ptr = (*time).ob_type;
Py_DECREF(time);
ptr
}
#[cfg(Py_3_9)]
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
unsafe fn look_up_zoneinfo_type() -> *mut PyTypeObject {
let module = PyImport_ImportModule("zoneinfo\0".as_ptr() as *const c_char);
let module_dict = PyObject_GenericGetDict(module, null_mut());
let ptr = PyMapping_GetItemString(module_dict, "ZoneInfo\0".as_ptr() as *const c_char)
as *mut PyTypeObject;
Py_DECREF(module_dict);
Py_DECREF(module);
ptr
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/pyobject.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::deserialize::cache::*;
use crate::str::{hash_str, unicode_from_str};
use crate::typeref::{FALSE, NONE, TRUE};
use core::ptr::NonNull;
#[inline(always)]
pub fn get_unicode_key(key_str: &str) -> *mut pyo3_ffi::PyObject {
if unlikely!(key_str.len() > 64) {
let pyob = unicode_from_str(key_str);
hash_str(pyob);
pyob
} else {
let hash = cache_hash(key_str.as_bytes());
unsafe {
let entry = KEY_MAP
.get_mut()
.unwrap_or_else(|| unreachable!())
.entry(&hash)
.or_insert_with(
|| hash,
|| {
let pyob = unicode_from_str(key_str);
hash_str(pyob);
CachedKey::new(pyob)
},
);
entry.get()
}
}
}
#[allow(dead_code)]
#[inline(always)]
pub fn parse_bool(val: bool) -> NonNull<pyo3_ffi::PyObject> {
if val {
parse_true()
} else {
parse_false()
}
}
#[inline(always)]
pub fn parse_true() -> NonNull<pyo3_ffi::PyObject> {
nonnull!(use_immortal!(TRUE))
}
#[inline(always)]
pub fn parse_false() -> NonNull<pyo3_ffi::PyObject> {
nonnull!(use_immortal!(FALSE))
}
#[inline(always)]
pub fn parse_i64(val: i64) -> NonNull<pyo3_ffi::PyObject> {
nonnull!(ffi!(PyLong_FromLongLong(val)))
}
#[inline(always)]
pub fn parse_u64(val: u64) -> NonNull<pyo3_ffi::PyObject> {
nonnull!(ffi!(PyLong_FromUnsignedLongLong(val)))
}
#[inline(always)]
pub fn parse_f64(val: f64) -> NonNull<pyo3_ffi::PyObject> {
nonnull!(ffi!(PyFloat_FromDouble(val)))
}
#[inline(always)]
pub fn parse_none() -> NonNull<pyo3_ffi::PyObject> {
nonnull!(use_immortal!(NONE))
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/utf8.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::deserialize::DeserializeError;
use crate::ffi::*;
use crate::str::unicode_to_str;
use crate::typeref::{BYTEARRAY_TYPE, BYTES_TYPE, MEMORYVIEW_TYPE, STR_TYPE};
use crate::util::INVALID_STR;
use core::ffi::c_char;
use std::borrow::Cow;
#[cfg(all(target_arch = "x86_64", not(target_feature = "avx2")))]
fn is_valid_utf8(buf: &[u8]) -> bool {
if std::is_x86_feature_detected!("avx2") {
unsafe { simdutf8::basic::imp::x86::avx2::validate_utf8(buf).is_ok() }
} else {
encoding_rs::Encoding::utf8_valid_up_to(buf) == buf.len()
}
}
#[cfg(all(target_arch = "x86_64", target_feature = "avx2"))]
fn is_valid_utf8(buf: &[u8]) -> bool {
simdutf8::basic::from_utf8(buf).is_ok()
}
#[cfg(target_arch = "aarch64")]
fn is_valid_utf8(buf: &[u8]) -> bool {
simdutf8::basic::from_utf8(buf).is_ok()
}
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
fn is_valid_utf8(buf: &[u8]) -> bool {
std::str::from_utf8(buf).is_ok()
}
pub fn read_input_to_buf(
ptr: *mut pyo3_ffi::PyObject,
) -> Result<&'static [u8], DeserializeError<'static>> {
let obj_type_ptr = ob_type!(ptr);
let buffer: &[u8];
if is_type!(obj_type_ptr, BYTES_TYPE) {
buffer = unsafe {
core::slice::from_raw_parts(
PyBytes_AS_STRING(ptr) as *const u8,
PyBytes_GET_SIZE(ptr) as usize,
)
};
if !is_valid_utf8(buffer) {
return Err(DeserializeError::invalid(Cow::Borrowed(INVALID_STR)));
}
} else if is_type!(obj_type_ptr, STR_TYPE) {
let uni = unicode_to_str(ptr);
if unlikely!(uni.is_none()) {
return Err(DeserializeError::invalid(Cow::Borrowed(INVALID_STR)));
}
let as_str = uni.unwrap();
buffer = unsafe { core::slice::from_raw_parts(as_str.as_ptr(), as_str.len()) };
} else if unlikely!(is_type!(obj_type_ptr, MEMORYVIEW_TYPE)) {
let membuf = unsafe { PyMemoryView_GET_BUFFER(ptr) };
if unsafe { pyo3_ffi::PyBuffer_IsContiguous(membuf, b'C' as c_char) == 0 } {
return Err(DeserializeError::invalid(Cow::Borrowed(
"Input type memoryview must be a C contiguous buffer",
)));
}
buffer = unsafe {
core::slice::from_raw_parts((*membuf).buf as *const u8, (*membuf).len as usize)
};
if !is_valid_utf8(buffer) {
return Err(DeserializeError::invalid(Cow::Borrowed(INVALID_STR)));
}
} else if unlikely!(is_type!(obj_type_ptr, BYTEARRAY_TYPE)) {
buffer = unsafe {
core::slice::from_raw_parts(
ffi!(PyByteArray_AsString(ptr)) as *const u8,
ffi!(PyByteArray_Size(ptr)) as usize,
)
};
if !is_valid_utf8(buffer) {
return Err(DeserializeError::invalid(Cow::Borrowed(INVALID_STR)));
}
} else {
return Err(DeserializeError::invalid(Cow::Borrowed(
"Input must be bytes, bytearray, memoryview, or str",
)));
}
if unlikely!(buffer.is_empty()) {
Err(DeserializeError::invalid(Cow::Borrowed(
"Input is a zero-length, empty document",
)))
} else {
Ok(buffer)
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/cache.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use associative_cache::{AssociativeCache, Capacity2048, HashDirectMapped, RoundRobinReplacement};
use core::ffi::c_void;
use once_cell::unsync::OnceCell;
#[repr(transparent)]
pub struct CachedKey {
ptr: *mut c_void,
}
unsafe impl Send for CachedKey {}
unsafe impl Sync for CachedKey {}
impl CachedKey {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> CachedKey {
CachedKey {
ptr: ptr as *mut c_void,
}
}
pub fn get(&mut self) -> *mut pyo3_ffi::PyObject {
let ptr = self.ptr as *mut pyo3_ffi::PyObject;
debug_assert!(ffi!(Py_REFCNT(ptr)) >= 1);
ffi!(Py_INCREF(ptr));
ptr
}
}
impl Drop for CachedKey {
fn drop(&mut self) {
ffi!(Py_DECREF(self.ptr as *mut pyo3_ffi::PyObject));
}
}
pub type KeyMap =
AssociativeCache<u64, CachedKey, Capacity2048, HashDirectMapped, RoundRobinReplacement>;
pub static mut KEY_MAP: OnceCell<KeyMap> = OnceCell::new();
#[inline(always)]
pub fn cache_hash(key: &[u8]) -> u64 {
assume!(key.len() <= 64);
xxhash_rust::xxh3::xxh3_64(key)
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/deserializer.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::deserialize::utf8::read_input_to_buf;
use crate::deserialize::DeserializeError;
use crate::typeref::EMPTY_UNICODE;
use core::ptr::NonNull;
pub fn deserialize(
ptr: *mut pyo3_ffi::PyObject,
) -> Result<NonNull<pyo3_ffi::PyObject>, DeserializeError<'static>> {
debug_assert!(ffi!(Py_REFCNT(ptr)) >= 1);
let buffer = read_input_to_buf(ptr)?;
if unlikely!(buffer.len() == 2) {
if buffer == b"[]" {
return Ok(nonnull!(ffi!(PyList_New(0))));
} else if buffer == b"{}" {
return Ok(nonnull!(ffi!(PyDict_New())));
} else if buffer == b"\"\"" {
unsafe { return Ok(nonnull!(use_immortal!(EMPTY_UNICODE))) }
}
}
let buffer_str = unsafe { std::str::from_utf8_unchecked(buffer) };
crate::deserialize::backend::deserialize(buffer_str)
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/error.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use std::borrow::Cow;
pub struct DeserializeError<'a> {
pub message: Cow<'a, str>,
#[cfg(not(feature = "yyjson"))]
pub line: usize, // start at 1
#[cfg(not(feature = "yyjson"))]
pub column: usize, // start at 1
pub data: Option<&'a str>,
#[cfg(feature = "yyjson")]
pub pos: i64,
}
impl<'a> DeserializeError<'a> {
#[cold]
pub fn invalid(message: Cow<'a, str>) -> Self {
DeserializeError {
message: message,
#[cfg(not(feature = "yyjson"))]
line: 0,
#[cfg(not(feature = "yyjson"))]
column: 0,
data: None,
#[cfg(feature = "yyjson")]
pos: 0,
}
}
#[cold]
#[cfg(not(feature = "yyjson"))]
pub fn from_json(message: Cow<'a, str>, line: usize, column: usize, data: &'a str) -> Self {
DeserializeError {
message,
line,
column,
data: Some(data),
}
}
#[cold]
#[cfg(feature = "yyjson")]
pub fn from_yyjson(message: Cow<'a, str>, pos: i64, data: &'a str) -> Self {
DeserializeError {
message: message,
data: Some(data),
pos: pos,
}
}
/// Return position of the error in the deserialized data
#[cold]
#[cfg(feature = "yyjson")]
#[cfg_attr(feature = "optimize", optimize(size))]
pub fn pos(&self) -> i64 {
match self.data {
Some(as_str) => as_str[0..self.pos as usize].chars().count() as i64,
None => 0,
}
}
/// Return position of the error in the deserialized data
#[cold]
#[cfg(not(feature = "yyjson"))]
#[cfg_attr(feature = "optimize", optimize(size))]
pub fn pos(&self) -> i64 {
if self.line == 0 || self.data.is_none() {
return 1;
}
let val = self.data.unwrap()
.split('\n')
// take only the relevant lines
.take(self.line)
.enumerate()
.map(|(idx, s)| {
if idx == self.line - 1 {
// Last line: only characters until the column of the error are relevant.
// Note: Rust uses bytes whereas Python uses chars: we hence cannot
// directly use the `column` field
if self.column == 0 { return 0; }
// Find a column we can safely slice on
let mut column = self.column - 1;
while column > 0 && !s.is_char_boundary(column) {
column -= 1;
}
let chars_count = s[..column].chars().count();
if chars_count == s.chars().count() - 1 {
chars_count + 1
} else {
chars_count
}
} else {
// Other lines
s.chars().count()
}
})
.sum::<usize>()
// add missed '\n' characters
+ (self.line - 1);
val as i64
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
mod backend;
mod cache;
mod deserializer;
mod error;
mod pyobject;
mod utf8;
pub use cache::{KeyMap, KEY_MAP};
pub use deserializer::deserialize;
pub use error::DeserializeError;
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/backend/json.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::deserialize::pyobject::*;
use crate::deserialize::DeserializeError;
use crate::str::unicode_from_str;
use core::ptr::NonNull;
use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor};
use smallvec::SmallVec;
use std::borrow::Cow;
use std::fmt;
pub(crate) fn deserialize(
data: &'static str,
) -> Result<NonNull<pyo3_ffi::PyObject>, DeserializeError<'static>> {
let mut deserializer = serde_json::Deserializer::from_str(data);
let seed = JsonValue {};
match seed.deserialize(&mut deserializer) {
Ok(obj) => {
deserializer.end().map_err(|e| {
DeserializeError::from_json(Cow::Owned(e.to_string()), e.line(), e.column(), data)
})?;
Ok(obj)
}
Err(e) => Err(DeserializeError::from_json(
Cow::Owned(e.to_string()),
e.line(),
e.column(),
data,
)),
}
}
#[derive(Clone, Copy)]
struct JsonValue;
impl<'de> DeserializeSeed<'de> for JsonValue {
type Value = NonNull<pyo3_ffi::PyObject>;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for JsonValue {
type Value = NonNull<pyo3_ffi::PyObject>;
fn expecting(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
Ok(())
}
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(parse_none())
}
fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(parse_bool(value))
}
fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(parse_i64(value))
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(parse_u64(value))
}
fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(parse_f64(value))
}
fn visit_borrowed_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(nonnull!(unicode_from_str(value)))
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(nonnull!(unicode_from_str(value)))
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: SeqAccess<'de>,
{
match seq.next_element_seed(self) {
Ok(None) => Ok(nonnull!(ffi!(PyList_New(0)))),
Ok(Some(elem)) => {
let mut elements: SmallVec<[*mut pyo3_ffi::PyObject; 8]> =
SmallVec::with_capacity(8);
elements.push(elem.as_ptr());
while let Some(elem) = seq.next_element_seed(self)? {
elements.push(elem.as_ptr());
}
let ptr = ffi!(PyList_New(elements.len() as isize));
for (i, &obj) in elements.iter().enumerate() {
ffi!(PyList_SET_ITEM(ptr, i as isize, obj));
}
Ok(nonnull!(ptr))
}
Err(err) => Result::Err(err),
}
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: MapAccess<'de>,
{
let dict_ptr = ffi!(PyDict_New());
while let Some(key) = map.next_key::<Cow<str>>()? {
let pykey = get_unicode_key(&key);
let pyval = map.next_value_seed(self)?;
let _ = unsafe {
pyo3_ffi::_PyDict_SetItem_KnownHash(
dict_ptr,
pykey,
pyval.as_ptr(),
str_hash!(pykey),
)
};
reverse_pydict_incref!(pykey);
reverse_pydict_incref!(pyval.as_ptr());
}
Ok(nonnull!(dict_ptr))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/backend/yyjson.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::deserialize::pyobject::*;
use crate::deserialize::DeserializeError;
use crate::ffi::yyjson::*;
use crate::str::unicode_from_str;
use crate::typeref::{yyjson_init, YYJSON_ALLOC, YYJSON_BUFFER_SIZE};
use core::ffi::c_char;
use core::ptr::{null, null_mut, NonNull};
use std::borrow::Cow;
const YYJSON_TAG_BIT: u8 = 8;
const YYJSON_VAL_SIZE: usize = core::mem::size_of::<yyjson_val>();
const TAG_ARRAY: u8 = 0b00000110;
const TAG_DOUBLE: u8 = 0b00010100;
const TAG_FALSE: u8 = 0b00000011;
const TAG_INT64: u8 = 0b00001100;
const TAG_NULL: u8 = 0b00000010;
const TAG_OBJECT: u8 = 0b00000111;
const TAG_STRING: u8 = 0b00000101;
const TAG_TRUE: u8 = 0b00001011;
const TAG_UINT64: u8 = 0b00000100;
macro_rules! is_yyjson_tag {
($elem:expr, $tag:expr) => {
unsafe { (*$elem).tag as u8 == $tag }
};
}
fn yyjson_doc_get_root(doc: *mut yyjson_doc) -> *mut yyjson_val {
unsafe { (*doc).root }
}
fn unsafe_yyjson_get_len(val: *mut yyjson_val) -> usize {
unsafe { ((*val).tag >> YYJSON_TAG_BIT) as usize }
}
fn unsafe_yyjson_get_first(ctn: *mut yyjson_val) -> *mut yyjson_val {
unsafe { ctn.add(1) }
}
fn yyjson_read_max_memory_usage(len: usize) -> usize {
(12 * len) + 256
}
fn unsafe_yyjson_is_ctn(val: *mut yyjson_val) -> bool {
unsafe { (*val).tag as u8 & 0b00000110 == 0b00000110 }
}
fn unsafe_yyjson_get_next_container(val: *mut yyjson_val) -> *mut yyjson_val {
unsafe { ((val as *mut u8).add((*val).uni.ofs)) as *mut yyjson_val }
}
fn unsafe_yyjson_get_next_non_container(val: *mut yyjson_val) -> *mut yyjson_val {
unsafe { ((val as *mut u8).add(YYJSON_VAL_SIZE)) as *mut yyjson_val }
}
pub(crate) fn deserialize(
data: &'static str,
) -> Result<NonNull<pyo3_ffi::PyObject>, DeserializeError<'static>> {
let mut err = yyjson_read_err {
code: YYJSON_READ_SUCCESS,
msg: null(),
pos: 0,
};
let doc = if yyjson_read_max_memory_usage(data.len()) < YYJSON_BUFFER_SIZE {
read_doc_with_buffer(data, &mut err)
} else {
read_doc_default(data, &mut err)
};
if unlikely!(doc.is_null()) {
let msg: Cow<str> = unsafe { core::ffi::CStr::from_ptr(err.msg).to_string_lossy() };
Err(DeserializeError::from_yyjson(msg, err.pos as i64, data))
} else {
let val = yyjson_doc_get_root(doc);
if unlikely!(!unsafe_yyjson_is_ctn(val)) {
let pyval = match ElementType::from_tag(val) {
ElementType::String => parse_yy_string(val),
ElementType::Uint64 => parse_yy_u64(val),
ElementType::Int64 => parse_yy_i64(val),
ElementType::Double => parse_yy_f64(val),
ElementType::Null => parse_none(),
ElementType::True => parse_true(),
ElementType::False => parse_false(),
ElementType::Array => unreachable!(),
ElementType::Object => unreachable!(),
};
unsafe { yyjson_doc_free(doc) };
Ok(pyval)
} else if is_yyjson_tag!(val, TAG_ARRAY) {
let pyval = nonnull!(ffi!(PyList_New(unsafe_yyjson_get_len(val) as isize)));
if unsafe_yyjson_get_len(val) > 0 {
populate_yy_array(pyval.as_ptr(), val);
}
unsafe { yyjson_doc_free(doc) };
Ok(pyval)
} else {
let pyval = nonnull!(ffi!(_PyDict_NewPresized(
unsafe_yyjson_get_len(val) as isize
)));
if unsafe_yyjson_get_len(val) > 0 {
populate_yy_object(pyval.as_ptr(), val);
}
unsafe { yyjson_doc_free(doc) };
Ok(pyval)
}
}
}
fn read_doc_default(data: &'static str, err: &mut yyjson_read_err) -> *mut yyjson_doc {
unsafe { yyjson_read_opts(data.as_ptr() as *mut c_char, data.len(), null_mut(), err) }
}
fn read_doc_with_buffer(data: &'static str, err: &mut yyjson_read_err) -> *mut yyjson_doc {
unsafe {
yyjson_read_opts(
data.as_ptr() as *mut c_char,
data.len(),
&YYJSON_ALLOC.get_or_init(yyjson_init).alloc,
err,
)
}
}
enum ElementType {
String,
Uint64,
Int64,
Double,
Null,
True,
False,
Array,
Object,
}
impl ElementType {
fn from_tag(elem: *mut yyjson_val) -> Self {
match unsafe { (*elem).tag as u8 } {
TAG_STRING => Self::String,
TAG_UINT64 => Self::Uint64,
TAG_INT64 => Self::Int64,
TAG_DOUBLE => Self::Double,
TAG_NULL => Self::Null,
TAG_TRUE => Self::True,
TAG_FALSE => Self::False,
TAG_ARRAY => Self::Array,
TAG_OBJECT => Self::Object,
_ => unreachable!(),
}
}
}
#[inline(always)]
fn parse_yy_string(elem: *mut yyjson_val) -> NonNull<pyo3_ffi::PyObject> {
nonnull!(unicode_from_str(str_from_slice!(
(*elem).uni.str_ as *const u8,
unsafe_yyjson_get_len(elem)
)))
}
#[inline(always)]
fn parse_yy_u64(elem: *mut yyjson_val) -> NonNull<pyo3_ffi::PyObject> {
parse_u64(unsafe { (*elem).uni.u64_ })
}
#[inline(always)]
fn parse_yy_i64(elem: *mut yyjson_val) -> NonNull<pyo3_ffi::PyObject> {
parse_i64(unsafe { (*elem).uni.i64_ })
}
#[inline(always)]
fn parse_yy_f64(elem: *mut yyjson_val) -> NonNull<pyo3_ffi::PyObject> {
parse_f64(unsafe { (*elem).uni.f64_ })
}
macro_rules! append_to_list {
($dptr:expr, $pyval:expr) => {
unsafe {
core::ptr::write($dptr, $pyval);
$dptr = $dptr.add(1);
}
};
}
#[inline(never)]
fn populate_yy_array(list: *mut pyo3_ffi::PyObject, elem: *mut yyjson_val) {
unsafe {
let len = unsafe_yyjson_get_len(elem);
assume!(len >= 1);
let mut next = unsafe_yyjson_get_first(elem);
let mut dptr = (*(list as *mut pyo3_ffi::PyListObject)).ob_item;
for _ in 0..len {
let val = next;
if unlikely!(unsafe_yyjson_is_ctn(val)) {
next = unsafe_yyjson_get_next_container(val);
if is_yyjson_tag!(val, TAG_ARRAY) {
let pyval = ffi!(PyList_New(unsafe_yyjson_get_len(val) as isize));
append_to_list!(dptr, pyval);
if unsafe_yyjson_get_len(val) > 0 {
populate_yy_array(pyval, val);
}
} else {
let pyval = ffi!(_PyDict_NewPresized(unsafe_yyjson_get_len(val) as isize));
append_to_list!(dptr, pyval);
if unsafe_yyjson_get_len(val) > 0 {
populate_yy_object(pyval, val);
}
}
} else {
next = unsafe_yyjson_get_next_non_container(val);
let pyval = match ElementType::from_tag(val) {
ElementType::String => parse_yy_string(val),
ElementType::Uint64 => parse_yy_u64(val),
ElementType::Int64 => parse_yy_i64(val),
ElementType::Double => parse_yy_f64(val),
ElementType::Null => parse_none(),
ElementType::True => parse_true(),
ElementType::False => parse_false(),
ElementType::Array => unreachable!(),
ElementType::Object => unreachable!(),
};
append_to_list!(dptr, pyval.as_ptr());
}
}
}
}
macro_rules! add_to_dict {
($dict:expr, $pykey:expr, $pyval:expr) => {
unsafe { pyo3_ffi::_PyDict_SetItem_KnownHash($dict, $pykey, $pyval, str_hash!($pykey)) }
};
}
#[inline(never)]
fn populate_yy_object(dict: *mut pyo3_ffi::PyObject, elem: *mut yyjson_val) {
unsafe {
let len = unsafe_yyjson_get_len(elem);
assume!(len >= 1);
let mut next_key = unsafe_yyjson_get_first(elem);
let mut next_val = next_key.add(1);
for _ in 0..len {
let val = next_val;
let pykey = {
let key_str = str_from_slice!(
(*next_key).uni.str_ as *const u8,
unsafe_yyjson_get_len(next_key)
);
get_unicode_key(key_str)
};
if unlikely!(unsafe_yyjson_is_ctn(val)) {
next_key = unsafe_yyjson_get_next_container(val);
next_val = next_key.add(1);
if is_yyjson_tag!(val, TAG_ARRAY) {
let pyval = ffi!(PyList_New(unsafe_yyjson_get_len(val) as isize));
add_to_dict!(dict, pykey, pyval);
reverse_pydict_incref!(pykey);
reverse_pydict_incref!(pyval);
if unsafe_yyjson_get_len(val) > 0 {
populate_yy_array(pyval, val);
}
} else {
let pyval = ffi!(_PyDict_NewPresized(unsafe_yyjson_get_len(val) as isize));
add_to_dict!(dict, pykey, pyval);
reverse_pydict_incref!(pykey);
reverse_pydict_incref!(pyval);
if unsafe_yyjson_get_len(val) > 0 {
populate_yy_object(pyval, val);
}
}
} else {
next_key = unsafe_yyjson_get_next_non_container(val);
next_val = next_key.add(1);
let pyval = match ElementType::from_tag(val) {
ElementType::String => parse_yy_string(val),
ElementType::Uint64 => parse_yy_u64(val),
ElementType::Int64 => parse_yy_i64(val),
ElementType::Double => parse_yy_f64(val),
ElementType::Null => parse_none(),
ElementType::True => parse_true(),
ElementType::False => parse_false(),
ElementType::Array => unreachable!(),
ElementType::Object => unreachable!(),
};
add_to_dict!(dict, pykey, pyval.as_ptr());
reverse_pydict_incref!(pykey);
reverse_pydict_incref!(pyval.as_ptr());
}
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/deserialize/backend/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
#[cfg(not(feature = "yyjson"))]
mod json;
#[cfg(feature = "yyjson")]
mod yyjson;
#[cfg(feature = "yyjson")]
pub(crate) use yyjson::deserialize;
#[cfg(not(feature = "yyjson"))]
pub(crate) use json::deserialize;
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/str/ffi.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::ffi::c_void;
use pyo3_ffi::*;
// see unicodeobject.h for documentation
#[inline]
pub fn hash_str(op: *mut PyObject) -> Py_hash_t {
unsafe {
let data_ptr: *mut c_void = if (*op.cast::<PyASCIIObject>()).compact() == 1
&& (*op.cast::<PyASCIIObject>()).ascii() == 1
{
(op as *mut PyASCIIObject).offset(1) as *mut c_void
} else {
(op as *mut PyCompactUnicodeObject).offset(1) as *mut c_void
};
let num_bytes =
(*(op as *mut PyASCIIObject)).length * ((*(op as *mut PyASCIIObject)).kind()) as isize;
#[cfg(Py_3_14)]
let hash = pyo3_ffi::Py_HashBuffer(data_ptr, num_bytes);
#[cfg(not(Py_3_14))]
let hash = pyo3_ffi::_Py_HashBytes(data_ptr, num_bytes);
(*op.cast::<PyASCIIObject>()).hash = hash;
hash
}
}
#[inline(never)]
pub fn unicode_to_str_via_ffi(op: *mut PyObject) -> Option<&'static str> {
let mut str_size: pyo3_ffi::Py_ssize_t = 0;
let ptr = ffi!(PyUnicode_AsUTF8AndSize(op, &mut str_size)) as *const u8;
if unlikely!(ptr.is_null()) {
None
} else {
Some(str_from_slice!(ptr, str_size as usize))
}
}
#[inline]
pub fn unicode_to_str(op: *mut PyObject) -> Option<&'static str> {
unsafe {
if unlikely!((*op.cast::<PyASCIIObject>()).compact() == 0) {
unicode_to_str_via_ffi(op)
} else if (*op.cast::<PyASCIIObject>()).ascii() == 1 {
let ptr = op.cast::<PyASCIIObject>().offset(1) as *const u8;
let len = (*op.cast::<PyASCIIObject>()).length as usize;
Some(str_from_slice!(ptr, len))
} else if (*op.cast::<PyCompactUnicodeObject>()).utf8_length != 0 {
let ptr = (*op.cast::<PyCompactUnicodeObject>()).utf8 as *const u8;
let len = (*op.cast::<PyCompactUnicodeObject>()).utf8_length as usize;
Some(str_from_slice!(ptr, len))
} else {
unicode_to_str_via_ffi(op)
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/str/avx512.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::str::pyunicode_new::*;
use core::arch::x86_64::{
__m256i, _mm256_and_si256, _mm256_cmpgt_epu8_mask, _mm256_cmpneq_epi8_mask, _mm256_loadu_si256,
_mm256_mask_cmpneq_epi8_mask, _mm256_maskz_loadu_epi8, _mm256_max_epu8, _mm256_set1_epi8,
};
macro_rules! u8_as_i8 {
($val:expr) => {
core::mem::transmute::<u8, i8>($val)
};
}
macro_rules! impl_kind_simd_avx512vl {
($buf:expr) => {
unsafe {
const STRIDE: usize = 32;
assume!($buf.len() > 0);
let num_loops = $buf.len() / STRIDE;
let remainder = $buf.len() % STRIDE;
let remainder_mask: u32 = !(u32::MAX << remainder);
let mut str_vec =
_mm256_maskz_loadu_epi8(remainder_mask, $buf.as_bytes().as_ptr() as *const i8);
let sptr = $buf.as_bytes().as_ptr().add(remainder);
for i in 0..num_loops {
str_vec = _mm256_max_epu8(
str_vec,
_mm256_loadu_si256(sptr.add(STRIDE * i) as *const __m256i),
);
}
let vec_128 = _mm256_set1_epi8(u8_as_i8!(0b10000000));
if _mm256_cmpgt_epu8_mask(str_vec, vec_128) == 0 {
pyunicode_ascii($buf.as_bytes().as_ptr(), $buf.len())
} else {
let is_four = _mm256_cmpgt_epu8_mask(str_vec, _mm256_set1_epi8(u8_as_i8!(239))) > 0;
let is_not_latin =
_mm256_cmpgt_epu8_mask(str_vec, _mm256_set1_epi8(u8_as_i8!(195))) > 0;
let multibyte = _mm256_set1_epi8(u8_as_i8!(0b11000000));
let mut num_chars = popcnt!(_mm256_mask_cmpneq_epi8_mask(
remainder_mask,
_mm256_and_si256(
_mm256_maskz_loadu_epi8(
remainder_mask,
$buf.as_bytes().as_ptr() as *const i8
),
multibyte
),
vec_128
));
for i in 0..num_loops {
num_chars += popcnt!(_mm256_cmpneq_epi8_mask(
_mm256_and_si256(
_mm256_loadu_si256(sptr.add(STRIDE * i) as *const __m256i),
multibyte
),
vec_128,
)) as usize;
}
if is_four {
pyunicode_fourbyte($buf, num_chars)
} else if is_not_latin {
pyunicode_twobyte($buf, num_chars)
} else {
pyunicode_onebyte($buf, num_chars)
}
}
}
};
}
#[inline(never)]
#[cfg_attr(
feature = "avx512",
target_feature(enable = "avx512f,avx512bw,avx512vl,bmi2")
)]
pub unsafe fn create_str_impl_avx512vl(buf: &str) -> *mut pyo3_ffi::PyObject {
impl_kind_simd_avx512vl!(buf)
}
#[inline(always)]
pub fn unicode_from_str(buf: &str) -> *mut pyo3_ffi::PyObject {
unsafe {
if unlikely!(buf.is_empty()) {
return use_immortal!(crate::typeref::EMPTY_UNICODE);
}
if std::is_x86_feature_detected!("avx512vl") {
create_str_impl_avx512vl(buf)
} else {
super::scalar::unicode_from_str(buf)
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/str/scalar.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::str::pyunicode_new::*;
use crate::typeref::EMPTY_UNICODE;
#[inline(always)]
pub fn str_impl_kind_scalar(buf: &str, num_chars: usize) -> *mut pyo3_ffi::PyObject {
unsafe {
let len = buf.len();
assume!(len > 0);
if unlikely!(*(buf.as_bytes().as_ptr()) > 239) {
return pyunicode_fourbyte(buf, num_chars);
}
let sptr = buf.as_bytes().as_ptr();
let mut is_four = false;
let mut not_latin = false;
for i in 0..len {
is_four |= *sptr.add(i) > 239;
not_latin |= *sptr.add(i) > 195;
}
if is_four {
pyunicode_fourbyte(buf, num_chars)
} else if not_latin {
pyunicode_twobyte(buf, num_chars)
} else {
pyunicode_onebyte(buf, num_chars)
}
}
}
#[inline(never)]
pub fn unicode_from_str(buf: &str) -> *mut pyo3_ffi::PyObject {
if unlikely!(buf.is_empty()) {
return use_immortal!(EMPTY_UNICODE);
}
let num_chars = bytecount::num_chars(buf.as_bytes());
if buf.len() == num_chars {
pyunicode_ascii(buf.as_ptr(), num_chars)
} else {
str_impl_kind_scalar(buf, num_chars)
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/str/pyunicode_new.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use pyo3_ffi::{PyASCIIObject, PyCompactUnicodeObject};
#[inline(never)]
pub fn pyunicode_ascii(buf: *const u8, num_chars: usize) -> *mut pyo3_ffi::PyObject {
unsafe {
let ptr = ffi!(PyUnicode_New(num_chars as isize, 127));
let data_ptr = ptr.cast::<PyASCIIObject>().offset(1) as *mut u8;
core::ptr::copy_nonoverlapping(buf, data_ptr, num_chars);
core::ptr::write(data_ptr.add(num_chars), 0);
ptr
}
}
#[cold]
#[inline(never)]
pub fn pyunicode_onebyte(buf: &str, num_chars: usize) -> *mut pyo3_ffi::PyObject {
unsafe {
let ptr = ffi!(PyUnicode_New(num_chars as isize, 255));
let mut data_ptr = ptr.cast::<PyCompactUnicodeObject>().offset(1) as *mut u8;
for each in buf.chars().fuse() {
core::ptr::write(data_ptr, each as u8);
data_ptr = data_ptr.offset(1);
}
core::ptr::write(data_ptr, 0);
ptr
}
}
#[inline(never)]
pub fn pyunicode_twobyte(buf: &str, num_chars: usize) -> *mut pyo3_ffi::PyObject {
unsafe {
let ptr = ffi!(PyUnicode_New(num_chars as isize, 65535));
let mut data_ptr = ptr.cast::<PyCompactUnicodeObject>().offset(1) as *mut u16;
for each in buf.chars().fuse() {
core::ptr::write(data_ptr, each as u16);
data_ptr = data_ptr.offset(1);
}
core::ptr::write(data_ptr, 0);
ptr
}
}
#[inline(never)]
pub fn pyunicode_fourbyte(buf: &str, num_chars: usize) -> *mut pyo3_ffi::PyObject {
unsafe {
let ptr = ffi!(PyUnicode_New(num_chars as isize, 1114111));
let mut data_ptr = ptr.cast::<PyCompactUnicodeObject>().offset(1) as *mut u32;
for each in buf.chars().fuse() {
core::ptr::write(data_ptr, each as u32);
data_ptr = data_ptr.offset(1);
}
core::ptr::write(data_ptr, 0);
ptr
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/str/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
#[cfg(feature = "avx512")]
mod avx512;
mod ffi;
mod pyunicode_new;
mod scalar;
#[cfg(not(feature = "avx512"))]
pub use scalar::unicode_from_str;
#[cfg(feature = "avx512")]
pub use avx512::unicode_from_str;
pub use ffi::*;
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/buffer.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::mem::MaybeUninit;
const BUFFER_LENGTH: usize = 64 - core::mem::size_of::<usize>();
/// For use to serialize fixed-size UUIDs and DateTime.
#[repr(align(64))]
pub struct SmallFixedBuffer {
idx: usize,
bytes: [MaybeUninit<u8>; BUFFER_LENGTH],
}
impl SmallFixedBuffer {
#[inline]
pub fn new() -> Self {
Self {
idx: 0,
bytes: [MaybeUninit::<u8>::uninit(); BUFFER_LENGTH],
}
}
#[inline]
pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(
(core::ptr::addr_of_mut!(self.bytes) as *mut u8).add(self.idx),
BUFFER_LENGTH - self.idx,
)
}
}
#[inline]
pub unsafe fn set_written(&mut self, len: usize) {
debug_assert!(self.idx + len < BUFFER_LENGTH);
self.idx += len;
}
#[inline]
pub fn push(&mut self, value: u8) {
debug_assert!(self.idx + 1 < BUFFER_LENGTH);
unsafe {
core::ptr::write(
(core::ptr::addr_of_mut!(self.bytes) as *mut u8).add(self.idx),
value,
);
self.idx += 1;
};
}
#[inline]
pub fn extend_from_slice(&mut self, slice: &[u8]) {
debug_assert!(self.idx + slice.len() < BUFFER_LENGTH);
unsafe {
core::ptr::copy_nonoverlapping(
slice.as_ptr(),
(core::ptr::addr_of_mut!(self.bytes) as *mut u8).add(self.idx),
slice.len(),
);
self.idx += slice.len();
}
}
#[inline]
pub fn as_ptr(&self) -> *const u8 {
core::ptr::addr_of!(self.bytes) as *const u8
}
#[inline]
pub fn len(&self) -> usize {
self.idx
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/state.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::*;
const RECURSION_SHIFT: usize = 24;
const RECURSION_MASK: u32 = 255 << RECURSION_SHIFT;
const DEFAULT_SHIFT: usize = 16;
const DEFAULT_MASK: u32 = 255 << DEFAULT_SHIFT;
#[repr(transparent)]
#[derive(Copy, Clone)]
pub struct SerializerState {
// recursion: u8,
// default_calls: u8,
// opts: u16,
state: u32,
}
impl SerializerState {
#[inline(always)]
pub fn new(opts: Opt) -> Self {
debug_assert!(opts < u16::MAX as u32);
Self { state: opts }
}
#[inline(always)]
pub fn opts(&self) -> u32 {
self.state
}
#[inline(always)]
pub fn recursion_limit(&self) -> bool {
self.state & RECURSION_MASK == RECURSION_MASK
}
#[inline(always)]
pub fn default_calls_limit(&self) -> bool {
self.state & DEFAULT_MASK == DEFAULT_MASK
}
#[inline(always)]
pub fn copy_for_recursive_call(&self) -> Self {
let opt = self.state & !RECURSION_MASK;
let recursion = (((self.state & RECURSION_MASK) >> RECURSION_SHIFT) + 1) << RECURSION_SHIFT;
Self {
state: opt | recursion,
}
}
#[inline(always)]
pub fn copy_for_default_call(&self) -> Self {
let opt = self.state & !DEFAULT_MASK;
let default_calls = (((self.state & DEFAULT_MASK) >> DEFAULT_SHIFT) + 1) << DEFAULT_SHIFT;
Self {
state: opt | default_calls,
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/obtype.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::{
Opt, PASSTHROUGH_DATACLASS, PASSTHROUGH_DATETIME, PASSTHROUGH_SUBCLASS, SERIALIZE_NUMPY,
};
use crate::serialize::per_type::{is_numpy_array, is_numpy_scalar};
use crate::typeref::{
BOOL_TYPE, DATACLASS_FIELDS_STR, DATETIME_TYPE, DATE_TYPE, DICT_TYPE, ENUM_TYPE, FLOAT_TYPE,
FRAGMENT_TYPE, INT_TYPE, LIST_TYPE, NONE_TYPE, STR_TYPE, TIME_TYPE, TUPLE_TYPE, UUID_TYPE,
};
#[repr(u32)]
pub enum ObType {
Str,
Int,
Bool,
None,
Float,
List,
Dict,
Datetime,
Date,
Time,
Tuple,
Uuid,
Dataclass,
NumpyScalar,
NumpyArray,
Enum,
StrSubclass,
Fragment,
Unknown,
}
pub fn pyobject_to_obtype(obj: *mut pyo3_ffi::PyObject, opts: Opt) -> ObType {
let ob_type = ob_type!(obj);
if is_class_by_type!(ob_type, STR_TYPE) {
ObType::Str
} else if is_class_by_type!(ob_type, INT_TYPE) {
ObType::Int
} else if is_class_by_type!(ob_type, BOOL_TYPE) {
ObType::Bool
} else if is_class_by_type!(ob_type, NONE_TYPE) {
ObType::None
} else if is_class_by_type!(ob_type, FLOAT_TYPE) {
ObType::Float
} else if is_class_by_type!(ob_type, LIST_TYPE) {
ObType::List
} else if is_class_by_type!(ob_type, DICT_TYPE) {
ObType::Dict
} else if is_class_by_type!(ob_type, DATETIME_TYPE) && opt_disabled!(opts, PASSTHROUGH_DATETIME)
{
ObType::Datetime
} else {
pyobject_to_obtype_unlikely(ob_type, opts)
}
}
#[cfg_attr(feature = "optimize", optimize(size))]
#[inline(never)]
pub fn pyobject_to_obtype_unlikely(ob_type: *mut pyo3_ffi::PyTypeObject, opts: Opt) -> ObType {
if is_class_by_type!(ob_type, UUID_TYPE) {
return ObType::Uuid;
} else if is_class_by_type!(ob_type, TUPLE_TYPE) {
return ObType::Tuple;
} else if is_class_by_type!(ob_type, FRAGMENT_TYPE) {
return ObType::Fragment;
}
if opt_disabled!(opts, PASSTHROUGH_DATETIME) {
if is_class_by_type!(ob_type, DATE_TYPE) {
return ObType::Date;
} else if is_class_by_type!(ob_type, TIME_TYPE) {
return ObType::Time;
}
}
if opt_disabled!(opts, PASSTHROUGH_SUBCLASS) {
if is_subclass_by_flag!(ob_type, Py_TPFLAGS_UNICODE_SUBCLASS) {
return ObType::StrSubclass;
} else if is_subclass_by_flag!(ob_type, Py_TPFLAGS_LONG_SUBCLASS) {
return ObType::Int;
} else if is_subclass_by_flag!(ob_type, Py_TPFLAGS_LIST_SUBCLASS) {
return ObType::List;
} else if is_subclass_by_flag!(ob_type, Py_TPFLAGS_DICT_SUBCLASS) {
return ObType::Dict;
}
}
if is_subclass_by_type!(ob_type, ENUM_TYPE) {
return ObType::Enum;
}
if opt_disabled!(opts, PASSTHROUGH_DATACLASS) && pydict_contains!(ob_type, DATACLASS_FIELDS_STR)
{
return ObType::Dataclass;
}
if unlikely!(opt_enabled!(opts, SERIALIZE_NUMPY)) {
if is_numpy_scalar(ob_type) {
return ObType::NumpyScalar;
} else if is_numpy_array(ob_type) {
return ObType::NumpyArray;
}
}
ObType::Unknown
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/serializer.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::{Opt, APPEND_NEWLINE, INDENT_2};
use crate::serialize::obtype::{pyobject_to_obtype, ObType};
use crate::serialize::per_type::{
BoolSerializer, DataclassGenericSerializer, Date, DateTime, DefaultSerializer,
DictGenericSerializer, EnumSerializer, FloatSerializer, FragmentSerializer, IntSerializer,
ListTupleSerializer, NoneSerializer, NumpyScalar, NumpySerializer, StrSerializer,
StrSubclassSerializer, Time, ZeroListSerializer, UUID,
};
use crate::serialize::state::SerializerState;
use crate::serialize::writer::{to_writer, to_writer_pretty, BytesWriter};
use core::ptr::NonNull;
use serde::ser::{Serialize, Serializer};
use std::io::Write;
pub fn serialize(
ptr: *mut pyo3_ffi::PyObject,
default: Option<NonNull<pyo3_ffi::PyObject>>,
opts: Opt,
) -> Result<NonNull<pyo3_ffi::PyObject>, String> {
let mut buf = BytesWriter::default();
let obj = PyObjectSerializer::new(ptr, SerializerState::new(opts), default);
let res = if opt_disabled!(opts, INDENT_2) {
to_writer(&mut buf, &obj)
} else {
to_writer_pretty(&mut buf, &obj)
};
match res {
Ok(_) => {
if opt_enabled!(opts, APPEND_NEWLINE) {
let _ = buf.write(b"\n");
}
Ok(buf.finish())
}
Err(err) => {
ffi!(Py_DECREF(buf.bytes_ptr().as_ptr()));
Err(err.to_string())
}
}
}
pub struct PyObjectSerializer {
pub ptr: *mut pyo3_ffi::PyObject,
pub state: SerializerState,
pub default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl PyObjectSerializer {
pub fn new(
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
PyObjectSerializer {
ptr: ptr,
state: state,
default: default,
}
}
}
impl Serialize for PyObjectSerializer {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match pyobject_to_obtype(self.ptr, self.state.opts()) {
ObType::Str => StrSerializer::new(self.ptr).serialize(serializer),
ObType::StrSubclass => StrSubclassSerializer::new(self.ptr).serialize(serializer),
ObType::Int => IntSerializer::new(self.ptr, self.state.opts()).serialize(serializer),
ObType::None => NoneSerializer::new().serialize(serializer),
ObType::Float => FloatSerializer::new(self.ptr).serialize(serializer),
ObType::Bool => BoolSerializer::new(self.ptr).serialize(serializer),
ObType::Datetime => DateTime::new(self.ptr, self.state.opts()).serialize(serializer),
ObType::Date => Date::new(self.ptr).serialize(serializer),
ObType::Time => Time::new(self.ptr, self.state.opts()).serialize(serializer),
ObType::Uuid => UUID::new(self.ptr).serialize(serializer),
ObType::Dict => {
DictGenericSerializer::new(self.ptr, self.state, self.default).serialize(serializer)
}
ObType::List => {
if ffi!(Py_SIZE(self.ptr)) == 0 {
ZeroListSerializer::new().serialize(serializer)
} else {
ListTupleSerializer::from_list(self.ptr, self.state, self.default)
.serialize(serializer)
}
}
ObType::Tuple => {
if ffi!(Py_SIZE(self.ptr)) == 0 {
ZeroListSerializer::new().serialize(serializer)
} else {
ListTupleSerializer::from_tuple(self.ptr, self.state, self.default)
.serialize(serializer)
}
}
ObType::Dataclass => DataclassGenericSerializer::new(self).serialize(serializer),
ObType::Enum => EnumSerializer::new(self).serialize(serializer),
ObType::NumpyArray => NumpySerializer::new(self).serialize(serializer),
ObType::NumpyScalar => {
NumpyScalar::new(self.ptr, self.state.opts()).serialize(serializer)
}
ObType::Fragment => FragmentSerializer::new(self.ptr).serialize(serializer),
ObType::Unknown => DefaultSerializer::new(self).serialize(serializer),
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/error.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::ffi::CStr;
use core::ptr::NonNull;
pub enum SerializeError {
DatetimeLibraryUnsupported,
DefaultRecursionLimit,
Integer53Bits,
Integer64Bits,
InvalidStr,
InvalidFragment,
KeyMustBeStr,
RecursionLimit,
TimeHasTzinfo,
DictIntegerKey64Bit,
DictKeyInvalidType,
NumpyMalformed,
NumpyNotCContiguous,
NumpyNotNativeEndian,
NumpyUnsupportedDatatype,
UnsupportedType(NonNull<pyo3_ffi::PyObject>),
}
impl std::fmt::Display for SerializeError {
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match *self {
SerializeError::DatetimeLibraryUnsupported => write!(f, "datetime's timezone library is not supported: use datetime.timezone.utc, pendulum, pytz, or dateutil"),
SerializeError::DefaultRecursionLimit => {
write!(f, "default serializer exceeds recursion limit")
}
SerializeError::Integer53Bits => write!(f, "Integer exceeds 53-bit range"),
SerializeError::Integer64Bits => write!(f, "Integer exceeds 64-bit range"),
SerializeError::InvalidStr => write!(f, "{}", crate::util::INVALID_STR),
SerializeError::InvalidFragment => write!(f, "orjson.Fragment's content is not of type bytes or str"),
SerializeError::KeyMustBeStr => write!(f, "Dict key must be str"),
SerializeError::RecursionLimit => write!(f, "Recursion limit reached"),
SerializeError::TimeHasTzinfo => write!(f, "datetime.time must not have tzinfo set"),
SerializeError::DictIntegerKey64Bit => {
write!(f, "Dict integer key must be within 64-bit range")
}
SerializeError::DictKeyInvalidType => {
write!(f, "Dict key must a type serializable with OPT_NON_STR_KEYS")
}
SerializeError::NumpyMalformed => write!(f, "numpy array is malformed"),
SerializeError::NumpyNotCContiguous => write!(
f,
"numpy array is not C contiguous; use ndarray.tolist() in default"
),
SerializeError::NumpyNotNativeEndian => write!(
f,
"numpy array is not native-endianness"
),
SerializeError::NumpyUnsupportedDatatype => {
write!(f, "unsupported datatype in numpy array")
}
SerializeError::UnsupportedType(ptr) => {
let name = unsafe { CStr::from_ptr((*ob_type!(ptr.as_ptr())).tp_name).to_string_lossy() };
write!(f, "Type is not JSON serializable: {}", name)
}
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
mod buffer;
mod error;
mod obtype;
mod per_type;
mod serializer;
mod state;
mod writer;
pub use serializer::{serialize, PyObjectSerializer};
pub use state::SerializerState;
pub use writer::{to_writer, WriteExt};
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/pyenum.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::serializer::PyObjectSerializer;
use crate::typeref::VALUE_STR;
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct EnumSerializer<'a> {
previous: &'a PyObjectSerializer,
}
impl<'a> EnumSerializer<'a> {
pub fn new(previous: &'a PyObjectSerializer) -> Self {
Self { previous: previous }
}
}
impl<'a> Serialize for EnumSerializer<'a> {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value = ffi!(PyObject_GetAttr(self.previous.ptr, VALUE_STR));
debug_assert!(ffi!(Py_REFCNT(value)) >= 2);
let ret = PyObjectSerializer::new(value, self.previous.state, self.previous.default)
.serialize(serializer);
ffi!(Py_DECREF(value));
ret
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/pybool.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct BoolSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl BoolSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
BoolSerializer { ptr: ptr }
}
}
impl Serialize for BoolSerializer {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bool(unsafe { self.ptr == crate::typeref::TRUE })
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/numpy.rs | use crate::opt::*;
use crate::serialize::buffer::SmallFixedBuffer;
use crate::serialize::error::SerializeError;
use crate::serialize::per_type::{
DateTimeError, DateTimeLike, DefaultSerializer, Offset, ZeroListSerializer,
};
use crate::serialize::serializer::PyObjectSerializer;
use crate::typeref::{load_numpy_types, ARRAY_STRUCT_STR, DESCR_STR, DTYPE_STR, NUMPY_TYPES};
use core::ffi::{c_char, c_int, c_void};
use jiff::civil::DateTime;
use jiff::Timestamp;
use pyo3_ffi::*;
use serde::ser::{self, Serialize, SerializeSeq, Serializer};
use std::fmt;
#[repr(transparent)]
pub struct NumpySerializer<'a> {
previous: &'a PyObjectSerializer,
}
impl<'a> NumpySerializer<'a> {
pub fn new(previous: &'a PyObjectSerializer) -> Self {
Self { previous: previous }
}
}
impl<'a> Serialize for NumpySerializer<'a> {
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match NumpyArray::new(self.previous.ptr, self.previous.state.opts()) {
Ok(val) => val.serialize(serializer),
Err(PyArrayError::Malformed) => err!(SerializeError::NumpyMalformed),
Err(PyArrayError::NotContiguous) | Err(PyArrayError::UnsupportedDataType)
if self.previous.default.is_some() =>
{
DefaultSerializer::new(self.previous).serialize(serializer)
}
Err(PyArrayError::NotContiguous) => {
err!(SerializeError::NumpyNotCContiguous)
}
Err(PyArrayError::NotNativeEndian) => {
err!(SerializeError::NumpyNotNativeEndian)
}
Err(PyArrayError::UnsupportedDataType) => {
err!(SerializeError::NumpyUnsupportedDatatype)
}
}
}
}
macro_rules! slice {
($ptr:expr, $size:expr) => {
unsafe { core::slice::from_raw_parts($ptr, $size) }
};
}
#[cold]
pub fn is_numpy_scalar(ob_type: *mut PyTypeObject) -> bool {
let numpy_types = unsafe { NUMPY_TYPES.get_or_init(load_numpy_types) };
if numpy_types.is_none() {
false
} else {
let scalar_types = unsafe { numpy_types.unwrap().as_ref() };
ob_type == scalar_types.float64
|| ob_type == scalar_types.float32
|| ob_type == scalar_types.float16
|| ob_type == scalar_types.int64
|| ob_type == scalar_types.int16
|| ob_type == scalar_types.int32
|| ob_type == scalar_types.int8
|| ob_type == scalar_types.uint64
|| ob_type == scalar_types.uint32
|| ob_type == scalar_types.uint8
|| ob_type == scalar_types.uint16
|| ob_type == scalar_types.bool_
|| ob_type == scalar_types.datetime64
}
}
#[cold]
pub fn is_numpy_array(ob_type: *mut PyTypeObject) -> bool {
let numpy_types = unsafe { NUMPY_TYPES.get_or_init(load_numpy_types) };
if numpy_types.is_none() {
false
} else {
let scalar_types = unsafe { numpy_types.unwrap().as_ref() };
unsafe { ob_type == scalar_types.array }
}
}
#[repr(C)]
pub struct PyCapsule {
pub ob_refcnt: Py_ssize_t,
pub ob_type: *mut PyTypeObject,
pub pointer: *mut c_void,
pub name: *const c_char,
pub context: *mut c_void,
pub destructor: *mut c_void, // should be typedef void (*PyCapsule_Destructor)(PyObject *);
}
// https://docs.scipy.org/doc/numpy/reference/arrays.interface.html#c.__array_struct__
const NPY_ARRAY_C_CONTIGUOUS: c_int = 0x1;
const NPY_ARRAY_NOTSWAPPED: c_int = 0x200;
#[repr(C)]
pub struct PyArrayInterface {
pub two: c_int,
pub nd: c_int,
pub typekind: c_char,
pub itemsize: c_int,
pub flags: c_int,
pub shape: *mut Py_intptr_t,
pub strides: *mut Py_intptr_t,
pub data: *mut c_void,
pub descr: *mut PyObject,
}
#[derive(Clone, Copy)]
pub enum ItemType {
BOOL,
DATETIME64(NumpyDatetimeUnit),
F16,
F32,
F64,
I8,
I16,
I32,
I64,
U8,
U16,
U32,
U64,
}
impl ItemType {
fn find(array: *mut PyArrayInterface, ptr: *mut PyObject) -> Option<ItemType> {
match unsafe { ((*array).typekind, (*array).itemsize) } {
(098, 1) => Some(ItemType::BOOL),
(077, 8) => {
let unit = NumpyDatetimeUnit::from_pyobject(ptr);
Some(ItemType::DATETIME64(unit))
}
(102, 2) => Some(ItemType::F16),
(102, 4) => Some(ItemType::F32),
(102, 8) => Some(ItemType::F64),
(105, 1) => Some(ItemType::I8),
(105, 2) => Some(ItemType::I16),
(105, 4) => Some(ItemType::I32),
(105, 8) => Some(ItemType::I64),
(117, 1) => Some(ItemType::U8),
(117, 2) => Some(ItemType::U16),
(117, 4) => Some(ItemType::U32),
(117, 8) => Some(ItemType::U64),
_ => None,
}
}
}
pub enum PyArrayError {
Malformed,
NotContiguous,
NotNativeEndian,
UnsupportedDataType,
}
// >>> arr = numpy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], numpy.int32)
// >>> arr.ndim
// 3
// >>> arr.shape
// (2, 2, 2)
// >>> arr.strides
// (16, 8, 4)
pub struct NumpyArray {
array: *mut PyArrayInterface,
position: Vec<isize>,
children: Vec<NumpyArray>,
depth: usize,
capsule: *mut PyCapsule,
kind: ItemType,
opts: Opt,
}
impl NumpyArray {
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
pub fn new(ptr: *mut PyObject, opts: Opt) -> Result<Self, PyArrayError> {
let capsule = ffi!(PyObject_GetAttr(ptr, ARRAY_STRUCT_STR));
let array = unsafe { (*(capsule as *mut PyCapsule)).pointer as *mut PyArrayInterface };
if unsafe { (*array).two != 2 } {
ffi!(Py_DECREF(capsule));
Err(PyArrayError::Malformed)
} else if unsafe { (*array).flags } & NPY_ARRAY_C_CONTIGUOUS != NPY_ARRAY_C_CONTIGUOUS {
ffi!(Py_DECREF(capsule));
Err(PyArrayError::NotContiguous)
} else if unsafe { (*array).flags } & NPY_ARRAY_NOTSWAPPED != NPY_ARRAY_NOTSWAPPED {
ffi!(Py_DECREF(capsule));
Err(PyArrayError::NotNativeEndian)
} else {
let num_dimensions = unsafe { (*array).nd as usize };
if num_dimensions == 0 {
ffi!(Py_DECREF(capsule));
return Err(PyArrayError::UnsupportedDataType);
}
match ItemType::find(array, ptr) {
None => {
ffi!(Py_DECREF(capsule));
Err(PyArrayError::UnsupportedDataType)
}
Some(kind) => {
let mut pyarray = NumpyArray {
array: array,
position: vec![0; num_dimensions],
children: Vec::with_capacity(num_dimensions),
depth: 0,
capsule: capsule as *mut PyCapsule,
kind: kind,
opts,
};
if pyarray.dimensions() > 1 {
pyarray.build();
}
Ok(pyarray)
}
}
}
}
#[cfg_attr(feature = "optimize", optimize(size))]
fn child_from_parent(&self, position: Vec<isize>, num_children: usize) -> Self {
let mut arr = NumpyArray {
array: self.array,
position: position,
children: Vec::with_capacity(num_children),
depth: self.depth + 1,
capsule: self.capsule,
kind: self.kind,
opts: self.opts,
};
arr.build();
arr
}
#[cfg_attr(feature = "optimize", optimize(size))]
fn build(&mut self) {
if self.depth < self.dimensions() - 1 {
for i in 0..self.shape()[self.depth] {
let mut position: Vec<isize> = self.position.to_vec();
position[self.depth] = i;
let num_children: usize = if self.depth < self.dimensions() - 2 {
self.shape()[self.depth + 1] as usize
} else {
0
};
self.children
.push(self.child_from_parent(position, num_children))
}
}
}
#[inline(always)]
fn data(&self) -> *const c_void {
let offset = self
.strides()
.iter()
.zip(self.position.iter().copied())
.take(self.depth)
.map(|(a, b)| a * b)
.sum::<isize>();
unsafe { (*self.array).data.offset(offset) }
}
fn num_items(&self) -> usize {
self.shape()[self.shape().len() - 1] as usize
}
fn dimensions(&self) -> usize {
unsafe { (*self.array).nd as usize }
}
fn shape(&self) -> &[isize] {
slice!((*self.array).shape as *const isize, self.dimensions())
}
fn strides(&self) -> &[isize] {
slice!((*self.array).strides as *const isize, self.dimensions())
}
}
impl Drop for NumpyArray {
fn drop(&mut self) {
if self.depth == 0 {
ffi!(Py_DECREF(self.array as *mut pyo3_ffi::PyObject));
ffi!(Py_DECREF(self.capsule as *mut pyo3_ffi::PyObject));
}
}
}
impl Serialize for NumpyArray {
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if unlikely!(!(self.depth >= self.dimensions() || self.shape()[self.depth] != 0)) {
ZeroListSerializer::new().serialize(serializer)
} else if !self.children.is_empty() {
let mut seq = serializer.serialize_seq(None).unwrap();
for child in &self.children {
seq.serialize_element(child).unwrap();
}
seq.end()
} else {
match self.kind {
ItemType::F64 => {
NumpyF64Array::new(slice!(self.data() as *const f64, self.num_items()))
.serialize(serializer)
}
ItemType::F32 => {
NumpyF32Array::new(slice!(self.data() as *const f32, self.num_items()))
.serialize(serializer)
}
ItemType::F16 => {
NumpyF16Array::new(slice!(self.data() as *const u16, self.num_items()))
.serialize(serializer)
}
ItemType::U64 => {
NumpyU64Array::new(slice!(self.data() as *const u64, self.num_items()))
.serialize(serializer)
}
ItemType::U32 => {
NumpyU32Array::new(slice!(self.data() as *const u32, self.num_items()))
.serialize(serializer)
}
ItemType::U16 => {
NumpyU16Array::new(slice!(self.data() as *const u16, self.num_items()))
.serialize(serializer)
}
ItemType::U8 => {
NumpyU8Array::new(slice!(self.data() as *const u8, self.num_items()))
.serialize(serializer)
}
ItemType::I64 => {
NumpyI64Array::new(slice!(self.data() as *const i64, self.num_items()))
.serialize(serializer)
}
ItemType::I32 => {
NumpyI32Array::new(slice!(self.data() as *const i32, self.num_items()))
.serialize(serializer)
}
ItemType::I16 => {
NumpyI16Array::new(slice!(self.data() as *const i16, self.num_items()))
.serialize(serializer)
}
ItemType::I8 => {
NumpyI8Array::new(slice!(self.data() as *const i8, self.num_items()))
.serialize(serializer)
}
ItemType::BOOL => {
NumpyBoolArray::new(slice!(self.data() as *const u8, self.num_items()))
.serialize(serializer)
}
ItemType::DATETIME64(unit) => NumpyDatetime64Array::new(
slice!(self.data() as *const i64, self.num_items()),
unit,
self.opts,
)
.serialize(serializer),
}
}
}
}
#[repr(transparent)]
struct NumpyF64Array<'a> {
data: &'a [f64],
}
impl<'a> NumpyF64Array<'a> {
fn new(data: &'a [f64]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyF64Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeF64 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeF64 {
obj: f64,
}
impl Serialize for DataTypeF64 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_f64(self.obj)
}
}
#[repr(transparent)]
struct NumpyF32Array<'a> {
data: &'a [f32],
}
impl<'a> NumpyF32Array<'a> {
fn new(data: &'a [f32]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyF32Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeF32 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
struct DataTypeF32 {
obj: f32,
}
impl Serialize for DataTypeF32 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_f32(self.obj)
}
}
#[repr(transparent)]
struct NumpyF16Array<'a> {
data: &'a [u16],
}
impl<'a> NumpyF16Array<'a> {
fn new(data: &'a [u16]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyF16Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeF16 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
struct DataTypeF16 {
obj: u16,
}
impl Serialize for DataTypeF16 {
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let as_f16 = half::f16::from_bits(self.obj);
serializer.serialize_f32(as_f16.to_f32())
}
}
#[repr(transparent)]
struct NumpyU64Array<'a> {
data: &'a [u64],
}
impl<'a> NumpyU64Array<'a> {
fn new(data: &'a [u64]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyU64Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeU64 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeU64 {
obj: u64,
}
impl Serialize for DataTypeU64 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u64(self.obj)
}
}
#[repr(transparent)]
struct NumpyU32Array<'a> {
data: &'a [u32],
}
impl<'a> NumpyU32Array<'a> {
fn new(data: &'a [u32]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyU32Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeU32 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeU32 {
obj: u32,
}
impl Serialize for DataTypeU32 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.obj)
}
}
#[repr(transparent)]
struct NumpyU16Array<'a> {
data: &'a [u16],
}
impl<'a> NumpyU16Array<'a> {
fn new(data: &'a [u16]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyU16Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeU16 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeU16 {
obj: u16,
}
impl Serialize for DataTypeU16 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.obj as u32)
}
}
#[repr(transparent)]
struct NumpyI64Array<'a> {
data: &'a [i64],
}
impl<'a> NumpyI64Array<'a> {
fn new(data: &'a [i64]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyI64Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeI64 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeI64 {
obj: i64,
}
impl Serialize for DataTypeI64 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i64(self.obj)
}
}
#[repr(transparent)]
struct NumpyI32Array<'a> {
data: &'a [i32],
}
impl<'a> NumpyI32Array<'a> {
fn new(data: &'a [i32]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyI32Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeI32 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeI32 {
obj: i32,
}
impl Serialize for DataTypeI32 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.obj)
}
}
#[repr(transparent)]
struct NumpyI16Array<'a> {
data: &'a [i16],
}
impl<'a> NumpyI16Array<'a> {
fn new(data: &'a [i16]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyI16Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeI16 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeI16 {
obj: i16,
}
impl Serialize for DataTypeI16 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.obj as i32)
}
}
#[repr(transparent)]
struct NumpyI8Array<'a> {
data: &'a [i8],
}
impl<'a> NumpyI8Array<'a> {
fn new(data: &'a [i8]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyI8Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeI8 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeI8 {
obj: i8,
}
impl Serialize for DataTypeI8 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.obj as i32)
}
}
#[repr(transparent)]
struct NumpyU8Array<'a> {
data: &'a [u8],
}
impl<'a> NumpyU8Array<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyU8Array<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeU8 { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeU8 {
obj: u8,
}
impl Serialize for DataTypeU8 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.obj as u32)
}
}
#[repr(transparent)]
struct NumpyBoolArray<'a> {
data: &'a [u8],
}
impl<'a> NumpyBoolArray<'a> {
fn new(data: &'a [u8]) -> Self {
Self { data }
}
}
impl<'a> Serialize for NumpyBoolArray<'a> {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
seq.serialize_element(&DataTypeBool { obj: each }).unwrap();
}
seq.end()
}
}
#[repr(transparent)]
pub struct DataTypeBool {
obj: u8,
}
impl Serialize for DataTypeBool {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bool(self.obj == 1)
}
}
pub struct NumpyScalar {
ptr: *mut pyo3_ffi::PyObject,
opts: Opt,
}
impl NumpyScalar {
pub fn new(ptr: *mut PyObject, opts: Opt) -> Self {
NumpyScalar { ptr, opts }
}
}
impl Serialize for NumpyScalar {
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
unsafe {
let ob_type = ob_type!(self.ptr);
let scalar_types =
unsafe { NUMPY_TYPES.get_or_init(load_numpy_types).unwrap().as_ref() };
if ob_type == scalar_types.float64 {
(*(self.ptr as *mut NumpyFloat64)).serialize(serializer)
} else if ob_type == scalar_types.float32 {
(*(self.ptr as *mut NumpyFloat32)).serialize(serializer)
} else if ob_type == scalar_types.float16 {
(*(self.ptr as *mut NumpyFloat16)).serialize(serializer)
} else if ob_type == scalar_types.int64 {
(*(self.ptr as *mut NumpyInt64)).serialize(serializer)
} else if ob_type == scalar_types.int32 {
(*(self.ptr as *mut NumpyInt32)).serialize(serializer)
} else if ob_type == scalar_types.int16 {
(*(self.ptr as *mut NumpyInt16)).serialize(serializer)
} else if ob_type == scalar_types.int8 {
(*(self.ptr as *mut NumpyInt8)).serialize(serializer)
} else if ob_type == scalar_types.uint64 {
(*(self.ptr as *mut NumpyUint64)).serialize(serializer)
} else if ob_type == scalar_types.uint32 {
(*(self.ptr as *mut NumpyUint32)).serialize(serializer)
} else if ob_type == scalar_types.uint16 {
(*(self.ptr as *mut NumpyUint16)).serialize(serializer)
} else if ob_type == scalar_types.uint8 {
(*(self.ptr as *mut NumpyUint8)).serialize(serializer)
} else if ob_type == scalar_types.bool_ {
(*(self.ptr as *mut NumpyBool)).serialize(serializer)
} else if ob_type == scalar_types.datetime64 {
let unit = NumpyDatetimeUnit::from_pyobject(self.ptr);
let obj = &*(self.ptr as *mut NumpyDatetime64);
let dt = unit
.datetime(obj.value, self.opts)
.map_err(NumpyDateTimeError::into_serde_err)?;
dt.serialize(serializer)
} else {
unreachable!()
}
}
}
}
#[repr(C)]
pub struct NumpyInt8 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: i8,
}
impl Serialize for NumpyInt8 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.value as i32)
}
}
#[repr(C)]
pub struct NumpyInt16 {
pub ob_refcnt: Py_ssize_t,
pub ob_type: *mut PyTypeObject,
pub value: i16,
}
impl Serialize for NumpyInt16 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.value as i32)
}
}
#[repr(C)]
pub struct NumpyInt32 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: i32,
}
impl Serialize for NumpyInt32 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i32(self.value)
}
}
#[repr(C)]
pub struct NumpyInt64 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: i64,
}
impl Serialize for NumpyInt64 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_i64(self.value)
}
}
#[repr(C)]
pub struct NumpyUint8 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: u8,
}
impl Serialize for NumpyUint8 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.value as u32)
}
}
#[repr(C)]
pub struct NumpyUint16 {
pub ob_refcnt: Py_ssize_t,
pub ob_type: *mut PyTypeObject,
pub value: u16,
}
impl Serialize for NumpyUint16 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.value as u32)
}
}
#[repr(C)]
pub struct NumpyUint32 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: u32,
}
impl Serialize for NumpyUint32 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u32(self.value)
}
}
#[repr(C)]
pub struct NumpyUint64 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: u64,
}
impl Serialize for NumpyUint64 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u64(self.value)
}
}
#[repr(C)]
pub struct NumpyFloat16 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: u16,
}
impl Serialize for NumpyFloat16 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let as_f16 = half::f16::from_bits(self.value);
serializer.serialize_f32(as_f16.to_f32())
}
}
#[repr(C)]
pub struct NumpyFloat32 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: f32,
}
impl Serialize for NumpyFloat32 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_f32(self.value)
}
}
#[repr(C)]
pub struct NumpyFloat64 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: f64,
}
impl Serialize for NumpyFloat64 {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_f64(self.value)
}
}
#[repr(C)]
pub struct NumpyBool {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: bool,
}
impl Serialize for NumpyBool {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bool(self.value)
}
}
/// This mimicks the units supported by numpy's datetime64 type.
///
/// See
/// https://github.com/numpy/numpy/blob/fc8e3bbe419748ac5c6b7f3d0845e4bafa74644b/numpy/core/include/numpy/ndarraytypes.h#L268-L282.
#[derive(Clone, Copy)]
pub enum NumpyDatetimeUnit {
NaT,
Years,
Months,
Weeks,
Days,
Hours,
Minutes,
Seconds,
Milliseconds,
Microseconds,
Nanoseconds,
Picoseconds,
Femtoseconds,
Attoseconds,
Generic,
}
impl fmt::Display for NumpyDatetimeUnit {
#[cold]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let unit = match self {
Self::NaT => "NaT",
Self::Years => "years",
Self::Months => "months",
Self::Weeks => "weeks",
Self::Days => "days",
Self::Hours => "hours",
Self::Minutes => "minutes",
Self::Seconds => "seconds",
Self::Milliseconds => "milliseconds",
Self::Microseconds => "microseconds",
Self::Nanoseconds => "nanoseconds",
Self::Picoseconds => "picoseconds",
Self::Femtoseconds => "femtoseconds",
Self::Attoseconds => "attoseconds",
Self::Generic => "generic",
};
write!(f, "{}", unit)
}
}
#[derive(Clone, Copy)]
enum NumpyDateTimeError {
UnsupportedUnit(NumpyDatetimeUnit),
Unrepresentable { unit: NumpyDatetimeUnit, val: i64 },
}
impl NumpyDateTimeError {
#[cold]
fn into_serde_err<T: ser::Error>(self) -> T {
let err = match self {
Self::UnsupportedUnit(unit) => format!("unsupported numpy.datetime64 unit: {}", unit),
Self::Unrepresentable { unit, val } => {
format!("unrepresentable numpy.datetime64: {} {}", val, unit)
}
};
ser::Error::custom(err)
}
}
macro_rules! to_jiff_datetime {
($timestamp:expr, $self:expr, $val:expr) => {
Ok(
($timestamp.map_err(|_| NumpyDateTimeError::Unrepresentable {
unit: *$self,
val: $val,
})?)
.to_zoned(jiff::tz::TimeZone::UTC)
.datetime(),
)
};
}
impl NumpyDatetimeUnit {
/// Create a `NumpyDatetimeUnit` from a pointer to a Python object holding a
/// numpy array.
///
/// This function must only be called with pointers to numpy arrays.
///
/// We need to look inside the `obj.dtype.descr` attribute of the Python
/// object rather than using the `descr` field of the `__array_struct__`
/// because that field isn't populated for datetime64 arrays; see
/// https://github.com/numpy/numpy/issues/5350.
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
fn from_pyobject(ptr: *mut PyObject) -> Self {
let dtype = ffi!(PyObject_GetAttr(ptr, DTYPE_STR));
let descr = ffi!(PyObject_GetAttr(dtype, DESCR_STR));
let el0 = ffi!(PyList_GET_ITEM(descr, 0));
let descr_str = ffi!(PyTuple_GET_ITEM(el0, 1));
let uni = crate::str::unicode_to_str(descr_str).unwrap();
if uni.len() < 5 {
return Self::NaT;
}
// unit descriptions are found at
// https://github.com/numpy/numpy/blob/b235f9e701e14ed6f6f6dcba885f7986a833743f/numpy/core/src/multiarray/datetime.c#L79-L96.
let ret = match &uni[4..uni.len() - 1] {
"Y" => Self::Years,
"M" => Self::Months,
"W" => Self::Weeks,
"D" => Self::Days,
"h" => Self::Hours,
"m" => Self::Minutes,
"s" => Self::Seconds,
"ms" => Self::Milliseconds,
"us" => Self::Microseconds,
"ns" => Self::Nanoseconds,
"ps" => Self::Picoseconds,
"fs" => Self::Femtoseconds,
"as" => Self::Attoseconds,
"generic" => Self::Generic,
_ => unreachable!(),
};
ffi!(Py_DECREF(dtype));
ffi!(Py_DECREF(descr));
ret
}
/// Return a `NumpyDatetime64Repr` for a value in array with this unit.
///
/// Returns an `Err(NumpyDateTimeError)` if the value is invalid for this unit.
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
fn datetime(&self, val: i64, opts: Opt) -> Result<NumpyDatetime64Repr, NumpyDateTimeError> {
match self {
Self::Years => Ok(DateTime::new(
(val + 1970)
.try_into()
.map_err(|_| NumpyDateTimeError::Unrepresentable { unit: *self, val })?,
1,
1,
0,
0,
0,
0,
)
.unwrap()),
Self::Months => Ok(DateTime::new(
(val / 12 + 1970)
.try_into()
.map_err(|_| NumpyDateTimeError::Unrepresentable { unit: *self, val })?,
(val % 12 + 1)
.try_into()
.map_err(|_| NumpyDateTimeError::Unrepresentable { unit: *self, val })?,
1,
0,
0,
0,
0,
)
.unwrap()),
Self::Weeks => {
to_jiff_datetime!(Timestamp::from_second(val * 7 * 24 * 60 * 60), self, val)
}
Self::Days => to_jiff_datetime!(Timestamp::from_second(val * 24 * 60 * 60), self, val),
Self::Hours => to_jiff_datetime!(Timestamp::from_second(val * 60 * 60), self, val),
Self::Minutes => to_jiff_datetime!(Timestamp::from_second(val * 60), self, val),
Self::Seconds => to_jiff_datetime!(Timestamp::from_second(val), self, val),
Self::Milliseconds => to_jiff_datetime!(Timestamp::from_millisecond(val), self, val),
Self::Microseconds => to_jiff_datetime!(Timestamp::from_microsecond(val), self, val),
Self::Nanoseconds => {
to_jiff_datetime!(Timestamp::from_nanosecond(val as i128), self, val)
}
_ => Err(NumpyDateTimeError::UnsupportedUnit(*self)),
}
.map(|dt| NumpyDatetime64Repr { dt, opts })
}
}
struct NumpyDatetime64Array<'a> {
data: &'a [i64],
unit: NumpyDatetimeUnit,
opts: Opt,
}
impl<'a> NumpyDatetime64Array<'a> {
fn new(data: &'a [i64], unit: NumpyDatetimeUnit, opts: Opt) -> Self {
Self { data, unit, opts }
}
}
impl<'a> Serialize for NumpyDatetime64Array<'a> {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None).unwrap();
for &each in self.data.iter() {
let dt = self
.unit
.datetime(each, self.opts)
.map_err(NumpyDateTimeError::into_serde_err)?;
seq.serialize_element(&dt).unwrap();
}
seq.end()
}
}
#[repr(C)]
pub struct NumpyDatetime64 {
ob_refcnt: Py_ssize_t,
ob_type: *mut PyTypeObject,
value: i64,
}
macro_rules! forward_inner {
($meth: ident, $ty: ident) => {
fn $meth(&self) -> $ty {
self.dt.$meth() as $ty
}
};
}
struct NumpyDatetime64Repr {
dt: DateTime,
opts: Opt,
}
impl DateTimeLike for NumpyDatetime64Repr {
forward_inner!(year, i32);
forward_inner!(month, u8);
forward_inner!(day, u8);
forward_inner!(hour, u8);
forward_inner!(minute, u8);
forward_inner!(second, u8);
fn nanosecond(&self) -> u32 {
self.dt.subsec_nanosecond() as u32
}
fn microsecond(&self) -> u32 {
self.nanosecond() / 1_000
}
fn has_tz(&self) -> bool {
false
}
fn slow_offset(&self) -> Result<Offset, DateTimeError> {
unreachable!()
}
fn offset(&self) -> Result<Offset, DateTimeError> {
Ok(Offset::default())
}
}
impl Serialize for NumpyDatetime64Repr {
#[cold]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut buf = SmallFixedBuffer::new();
let _ = self.write_buf(&mut buf, self.opts);
serializer.collect_str(str_from_slice!(buf.as_ptr(), buf.len()))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/list.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::error::SerializeError;
use crate::serialize::obtype::{pyobject_to_obtype, ObType};
use crate::serialize::per_type::{
BoolSerializer, DataclassGenericSerializer, Date, DateTime, DefaultSerializer,
DictGenericSerializer, EnumSerializer, FloatSerializer, FragmentSerializer, IntSerializer,
NoneSerializer, NumpyScalar, NumpySerializer, StrSerializer, StrSubclassSerializer, Time, UUID,
};
use crate::serialize::serializer::PyObjectSerializer;
use crate::serialize::state::SerializerState;
use crate::typeref::*;
use core::ptr::NonNull;
use serde::ser::{Serialize, SerializeSeq, Serializer};
pub struct ZeroListSerializer;
impl ZeroListSerializer {
pub const fn new() -> Self {
Self {}
}
}
impl Serialize for ZeroListSerializer {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bytes(b"[]")
}
}
pub struct ListTupleSerializer {
data_ptr: *const *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
len: usize,
}
impl ListTupleSerializer {
pub fn from_list(
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
debug_assert!(
is_type!(ob_type!(ptr), LIST_TYPE)
|| is_subclass_by_flag!(ob_type!(ptr), Py_TPFLAGS_LIST_SUBCLASS)
);
let data_ptr = unsafe { (*(ptr as *mut pyo3_ffi::PyListObject)).ob_item };
let len = ffi!(Py_SIZE(ptr)) as usize;
Self {
data_ptr: data_ptr,
len: len,
state: state.copy_for_recursive_call(),
default: default,
}
}
pub fn from_tuple(
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
debug_assert!(
is_type!(ob_type!(ptr), TUPLE_TYPE)
|| is_subclass_by_flag!(ob_type!(ptr), Py_TPFLAGS_TUPLE_SUBCLASS)
);
let data_ptr = unsafe { (*(ptr as *mut pyo3_ffi::PyTupleObject)).ob_item.as_ptr() };
let len = ffi!(Py_SIZE(ptr)) as usize;
Self {
data_ptr: data_ptr,
len: len,
state: state.copy_for_recursive_call(),
default: default,
}
}
}
impl Serialize for ListTupleSerializer {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if unlikely!(self.state.recursion_limit()) {
err!(SerializeError::RecursionLimit)
}
debug_assert!(self.len >= 1);
let mut seq = serializer.serialize_seq(None).unwrap();
for idx in 0..self.len {
let value = unsafe { *((self.data_ptr).add(idx)) };
match pyobject_to_obtype(value, self.state.opts()) {
ObType::Str => {
seq.serialize_element(&StrSerializer::new(value))?;
}
ObType::StrSubclass => {
seq.serialize_element(&StrSubclassSerializer::new(value))?;
}
ObType::Int => {
seq.serialize_element(&IntSerializer::new(value, self.state.opts()))?;
}
ObType::None => {
seq.serialize_element(&NoneSerializer::new()).unwrap();
}
ObType::Float => {
seq.serialize_element(&FloatSerializer::new(value))?;
}
ObType::Bool => {
seq.serialize_element(&BoolSerializer::new(value)).unwrap();
}
ObType::Datetime => {
seq.serialize_element(&DateTime::new(value, self.state.opts()))?;
}
ObType::Date => {
seq.serialize_element(&Date::new(value))?;
}
ObType::Time => {
seq.serialize_element(&Time::new(value, self.state.opts()))?;
}
ObType::Uuid => {
seq.serialize_element(&UUID::new(value)).unwrap();
}
ObType::Dict => {
let pyvalue = DictGenericSerializer::new(value, self.state, self.default);
seq.serialize_element(&pyvalue)?;
}
ObType::List => {
if ffi!(Py_SIZE(value)) == 0 {
seq.serialize_element(&ZeroListSerializer::new()).unwrap();
} else {
let pyvalue =
ListTupleSerializer::from_list(value, self.state, self.default);
seq.serialize_element(&pyvalue)?;
}
}
ObType::Tuple => {
if ffi!(Py_SIZE(value)) == 0 {
seq.serialize_element(&ZeroListSerializer::new()).unwrap();
} else {
let pyvalue =
ListTupleSerializer::from_tuple(value, self.state, self.default);
seq.serialize_element(&pyvalue)?;
}
}
ObType::Dataclass => {
seq.serialize_element(&DataclassGenericSerializer::new(
&PyObjectSerializer::new(value, self.state, self.default),
))?;
}
ObType::Enum => {
seq.serialize_element(&EnumSerializer::new(&PyObjectSerializer::new(
value,
self.state,
self.default,
)))?;
}
ObType::NumpyArray => {
seq.serialize_element(&NumpySerializer::new(&PyObjectSerializer::new(
value,
self.state,
self.default,
)))?;
}
ObType::NumpyScalar => {
seq.serialize_element(&NumpyScalar::new(value, self.state.opts()))?;
}
ObType::Fragment => {
seq.serialize_element(&FragmentSerializer::new(value))?;
}
ObType::Unknown => {
seq.serialize_element(&DefaultSerializer::new(&PyObjectSerializer::new(
value,
self.state,
self.default,
)))?;
}
}
}
seq.end()
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/int.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::{Opt, STRICT_INTEGER};
use crate::serialize::error::SerializeError;
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;
pub struct IntSerializer {
ptr: *mut pyo3_ffi::PyObject,
opts: Opt,
}
impl IntSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject, opts: Opt) -> Self {
IntSerializer {
ptr: ptr,
opts: opts,
}
}
}
impl Serialize for IntSerializer {
#[inline(always)]
#[cfg(feature = "inline_int")]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
unsafe {
if crate::ffi::pylong_is_zero(self.ptr) {
return serializer.serialize_bytes(b"0");
}
let is_signed = !crate::ffi::pylong_is_unsigned(self.ptr) as i32;
if crate::ffi::pylong_fits_in_i32(self.ptr) {
if is_signed == 0 {
serializer.serialize_u64(crate::ffi::pylong_get_inline_value(self.ptr) as u64)
} else {
serializer.serialize_i64(crate::ffi::pylong_get_inline_value(self.ptr) as i64)
}
} else {
let mut buffer: [u8; 8] = [0; 8];
let ret = pyo3_ffi::_PyLong_AsByteArray(
self.ptr as *mut pyo3_ffi::PyLongObject,
buffer.as_mut_ptr() as *mut core::ffi::c_uchar,
8,
1,
is_signed,
);
if unlikely!(ret == -1) {
ffi!(PyErr_Clear());
err!(SerializeError::Integer64Bits)
}
if is_signed == 0 {
let val = core::mem::transmute::<[u8; 8], u64>(buffer);
if unlikely!(opt_enabled!(self.opts, STRICT_INTEGER))
&& val > STRICT_INT_MAX as u64
{
err!(SerializeError::Integer53Bits)
}
serializer.serialize_u64(val)
} else {
let val = core::mem::transmute::<[u8; 8], i64>(buffer);
if unlikely!(opt_enabled!(self.opts, STRICT_INTEGER))
&& !(STRICT_INT_MIN..=STRICT_INT_MAX).contains(&val)
{
err!(SerializeError::Integer53Bits)
}
serializer.serialize_i64(val)
}
}
}
}
#[inline(always)]
#[cfg(not(feature = "inline_int"))]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
unsafe {
if crate::ffi::pylong_is_unsigned(self.ptr) {
let val = ffi!(PyLong_AsUnsignedLongLong(self.ptr));
if unlikely!(val == u64::MAX) && !ffi!(PyErr_Occurred()).is_null() {
ffi!(PyErr_Clear());
err!(SerializeError::Integer64Bits)
} else if unlikely!(opt_enabled!(self.opts, STRICT_INTEGER))
&& val > STRICT_INT_MAX as u64
{
err!(SerializeError::Integer53Bits)
} else {
serializer.serialize_u64(val)
}
} else {
let val = ffi!(PyLong_AsLongLong(self.ptr));
if unlikely!(val == -1) && !ffi!(PyErr_Occurred()).is_null() {
ffi!(PyErr_Clear());
err!(SerializeError::Integer64Bits)
} else if unlikely!(opt_enabled!(self.opts, STRICT_INTEGER))
&& !(STRICT_INT_MIN..=STRICT_INT_MAX).contains(&val)
{
err!(SerializeError::Integer53Bits)
} else {
serializer.serialize_i64(val)
}
}
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/datetimelike.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::*;
use crate::serialize::buffer::SmallFixedBuffer;
pub enum DateTimeError {
LibraryUnsupported,
}
macro_rules! write_double_digit {
($buf:ident, $value:expr) => {
if $value < 10 {
$buf.push(b'0');
}
$buf.extend_from_slice(itoa::Buffer::new().format($value).as_bytes());
};
}
macro_rules! write_triple_digit {
($buf:ident, $value:expr) => {
if $value < 100 {
$buf.push(b'0');
}
if $value < 10 {
$buf.push(b'0');
}
$buf.extend_from_slice(itoa::Buffer::new().format($value).as_bytes());
};
}
#[derive(Default)]
pub struct Offset {
pub day: i32,
pub second: i32,
}
/// Trait providing a method to write a datetime-like object to a buffer in an RFC3339-compatible format.
///
/// The provided `write_buf` method does not allocate, and is faster
/// than writing to a heap-allocated string.
pub trait DateTimeLike {
/// Returns the year component of the datetime.
fn year(&self) -> i32;
/// Returns the month component of the datetime.
fn month(&self) -> u8;
/// Returns the day component of the datetime.
fn day(&self) -> u8;
/// Returns the hour component of the datetime.
fn hour(&self) -> u8;
/// Returns the minute component of the datetime.
fn minute(&self) -> u8;
/// Returns the second component of the datetime.
fn second(&self) -> u8;
/// Returns the number of microseconds since the whole non-leap second.
fn microsecond(&self) -> u32;
/// Returns the number of nanoseconds since the whole non-leap second.
fn nanosecond(&self) -> u32;
/// Is the object time-zone aware?
fn has_tz(&self) -> bool;
//// python3.8 or below implementation of offset()
fn slow_offset(&self) -> Result<Offset, DateTimeError>;
/// The offset of the timezone.
fn offset(&self) -> Result<Offset, DateTimeError>;
/// Write `self` to a buffer in RFC3339 format, using `opts` to
/// customise if desired.
#[inline(never)]
fn write_buf(&self, buf: &mut SmallFixedBuffer, opts: Opt) -> Result<(), DateTimeError> {
{
let year = self.year();
let mut yearbuf = itoa::Buffer::new();
let formatted = yearbuf.format(year);
if unlikely!(year < 1000) {
// date-fullyear = 4DIGIT
buf.extend_from_slice(&[b'0', b'0', b'0', b'0'][..(4 - formatted.len())]);
}
buf.extend_from_slice(formatted.as_bytes());
}
buf.push(b'-');
write_double_digit!(buf, self.month());
buf.push(b'-');
write_double_digit!(buf, self.day());
buf.push(b'T');
write_double_digit!(buf, self.hour());
buf.push(b':');
write_double_digit!(buf, self.minute());
buf.push(b':');
write_double_digit!(buf, self.second());
if opt_disabled!(opts, OMIT_MICROSECONDS) {
let microsecond = self.microsecond();
if microsecond != 0 {
buf.push(b'.');
write_triple_digit!(buf, microsecond / 1_000);
write_triple_digit!(buf, microsecond % 1_000);
// Don't support writing nanoseconds for now.
// If requested, something like the following should work,
// and `SmallFixedBuffer` needs at least length 35.
// let nanosecond = self.nanosecond();
// if nanosecond % 1_000 != 0 {
// write_triple_digit!(buf, nanosecond % 1_000);
// }
}
}
if self.has_tz() || opt_enabled!(opts, NAIVE_UTC) {
let offset = self.offset()?;
let mut offset_second = offset.second;
if offset_second == 0 {
if opt_enabled!(opts, UTC_Z) {
buf.push(b'Z');
} else {
buf.extend_from_slice(&[b'+', b'0', b'0', b':', b'0', b'0']);
}
} else {
// This branch is only really hit by the Python datetime implementation,
// since numpy datetimes are all converted to UTC.
if offset.day == -1 {
// datetime.timedelta(days=-1, seconds=68400) -> -05:00
buf.push(b'-');
offset_second = 86400 - offset_second;
} else {
// datetime.timedelta(seconds=37800) -> +10:30
buf.push(b'+');
}
let offset_minute = offset_second / 60;
let offset_hour = offset_minute / 60;
write_double_digit!(buf, offset_hour);
buf.push(b':');
let mut offset_minute_print = offset_minute % 60;
// https://tools.ietf.org/html/rfc3339#section-5.8
// "exactly 19 minutes and 32.13 seconds ahead of UTC"
// "closest representable UTC offset"
// "+20:00"
let offset_excess_second =
offset_second - (offset_minute_print * 60 + offset_hour * 3600);
if offset_excess_second >= 30 {
offset_minute_print += 1;
}
write_double_digit!(buf, offset_minute_print);
}
}
Ok(())
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/float.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct FloatSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl FloatSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
FloatSerializer { ptr: ptr }
}
}
impl Serialize for FloatSerializer {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_f64(ffi!(PyFloat_AS_DOUBLE(self.ptr)))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/datetime.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::*;
use crate::serialize::buffer::SmallFixedBuffer;
use crate::serialize::error::SerializeError;
use crate::serialize::per_type::datetimelike::{DateTimeError, DateTimeLike, Offset};
#[cfg(Py_3_9)]
use crate::typeref::ZONEINFO_TYPE;
use crate::typeref::{CONVERT_METHOD_STR, DST_STR, NORMALIZE_METHOD_STR, UTCOFFSET_METHOD_STR};
use serde::ser::{Serialize, Serializer};
macro_rules! write_double_digit {
($buf:ident, $value:ident) => {
if $value < 10 {
$buf.push(b'0');
}
$buf.extend_from_slice(itoa::Buffer::new().format($value).as_bytes());
};
}
macro_rules! write_microsecond {
($buf:ident, $microsecond:ident) => {
if $microsecond != 0 {
let mut buf = itoa::Buffer::new();
let formatted = buf.format($microsecond);
$buf.extend_from_slice(
&[b'.', b'0', b'0', b'0', b'0', b'0', b'0'][..(7 - formatted.len())],
);
$buf.extend_from_slice(formatted.as_bytes());
}
};
}
#[repr(transparent)]
pub struct Date {
ptr: *mut pyo3_ffi::PyObject,
}
impl Date {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
Date { ptr: ptr }
}
#[inline(never)]
pub fn write_buf(&self, buf: &mut SmallFixedBuffer) {
{
let year = ffi!(PyDateTime_GET_YEAR(self.ptr));
let mut yearbuf = itoa::Buffer::new();
let formatted = yearbuf.format(year);
if unlikely!(year < 1000) {
// date-fullyear = 4DIGIT
buf.extend_from_slice(&[b'0', b'0', b'0', b'0'][..(4 - formatted.len())]);
}
buf.extend_from_slice(formatted.as_bytes());
}
buf.push(b'-');
{
let month = ffi!(PyDateTime_GET_MONTH(self.ptr)) as u32;
write_double_digit!(buf, month);
}
buf.push(b'-');
{
let day = ffi!(PyDateTime_GET_DAY(self.ptr)) as u32;
write_double_digit!(buf, day);
}
}
}
impl Serialize for Date {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut buf = SmallFixedBuffer::new();
self.write_buf(&mut buf);
serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))
}
}
pub enum TimeError {
HasTimezone,
}
pub struct Time {
ptr: *mut pyo3_ffi::PyObject,
opts: Opt,
}
impl Time {
pub fn new(ptr: *mut pyo3_ffi::PyObject, opts: Opt) -> Self {
Time {
ptr: ptr,
opts: opts,
}
}
#[inline(never)]
pub fn write_buf(&self, buf: &mut SmallFixedBuffer) -> Result<(), TimeError> {
if unsafe { (*(self.ptr as *mut pyo3_ffi::PyDateTime_Time)).hastzinfo == 1 } {
return Err(TimeError::HasTimezone);
}
let hour = ffi!(PyDateTime_TIME_GET_HOUR(self.ptr)) as u8;
write_double_digit!(buf, hour);
buf.push(b':');
let minute = ffi!(PyDateTime_TIME_GET_MINUTE(self.ptr)) as u8;
write_double_digit!(buf, minute);
buf.push(b':');
let second = ffi!(PyDateTime_TIME_GET_SECOND(self.ptr)) as u8;
write_double_digit!(buf, second);
if opt_disabled!(self.opts, OMIT_MICROSECONDS) {
let microsecond = ffi!(PyDateTime_TIME_GET_MICROSECOND(self.ptr)) as u32;
write_microsecond!(buf, microsecond);
}
Ok(())
}
}
impl Serialize for Time {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut buf = SmallFixedBuffer::new();
if self.write_buf(&mut buf).is_err() {
err!(SerializeError::DatetimeLibraryUnsupported)
};
serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))
}
}
pub struct DateTime {
ptr: *mut pyo3_ffi::PyObject,
opts: Opt,
}
impl DateTime {
pub fn new(ptr: *mut pyo3_ffi::PyObject, opts: Opt) -> Self {
DateTime {
ptr: ptr,
opts: opts,
}
}
}
macro_rules! pydatetime_get {
($fn: ident, $pyfn: ident, $ty: ident) => {
fn $fn(&self) -> $ty {
ffi!($pyfn(self.ptr)) as $ty
}
};
}
impl DateTimeLike for DateTime {
pydatetime_get!(year, PyDateTime_GET_YEAR, i32);
pydatetime_get!(month, PyDateTime_GET_MONTH, u8);
pydatetime_get!(day, PyDateTime_GET_DAY, u8);
pydatetime_get!(hour, PyDateTime_DATE_GET_HOUR, u8);
pydatetime_get!(minute, PyDateTime_DATE_GET_MINUTE, u8);
pydatetime_get!(second, PyDateTime_DATE_GET_SECOND, u8);
pydatetime_get!(microsecond, PyDateTime_DATE_GET_MICROSECOND, u32);
fn nanosecond(&self) -> u32 {
self.microsecond() * 1_000
}
fn has_tz(&self) -> bool {
unsafe { (*(self.ptr as *mut pyo3_ffi::PyDateTime_DateTime)).hastzinfo == 1 }
}
fn slow_offset(&self) -> Result<Offset, DateTimeError> {
let tzinfo = ffi!(PyDateTime_DATE_GET_TZINFO(self.ptr));
if ffi!(PyObject_HasAttr(tzinfo, CONVERT_METHOD_STR)) == 1 {
// pendulum
let py_offset = call_method!(self.ptr, UTCOFFSET_METHOD_STR);
let offset = Offset {
second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),
day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),
};
ffi!(Py_DECREF(py_offset));
Ok(offset)
} else if ffi!(PyObject_HasAttr(tzinfo, NORMALIZE_METHOD_STR)) == 1 {
// pytz
let method_ptr = call_method!(tzinfo, NORMALIZE_METHOD_STR, self.ptr);
let py_offset = call_method!(method_ptr, UTCOFFSET_METHOD_STR);
ffi!(Py_DECREF(method_ptr));
let offset = Offset {
second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),
day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),
};
ffi!(Py_DECREF(py_offset));
Ok(offset)
} else if ffi!(PyObject_HasAttr(tzinfo, DST_STR)) == 1 {
// dateutil/arrow, datetime.timezone.utc
let py_offset = call_method!(tzinfo, UTCOFFSET_METHOD_STR, self.ptr);
let offset = Offset {
second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),
day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),
};
ffi!(Py_DECREF(py_offset));
Ok(offset)
} else {
Err(DateTimeError::LibraryUnsupported)
}
}
#[cfg(Py_3_9)]
fn offset(&self) -> Result<Offset, DateTimeError> {
if !self.has_tz() {
Ok(Offset::default())
} else {
let tzinfo = ffi!(PyDateTime_DATE_GET_TZINFO(self.ptr));
if unsafe { ob_type!(tzinfo) == ZONEINFO_TYPE } {
// zoneinfo
let py_offset = call_method!(tzinfo, UTCOFFSET_METHOD_STR, self.ptr);
let offset = Offset {
second: ffi!(PyDateTime_DELTA_GET_SECONDS(py_offset)),
day: ffi!(PyDateTime_DELTA_GET_DAYS(py_offset)),
};
ffi!(Py_DECREF(py_offset));
Ok(offset)
} else {
self.slow_offset()
}
}
}
#[cfg(not(Py_3_9))]
fn offset(&self) -> Result<Offset, DateTimeError> {
if !self.has_tz() {
Ok(Offset::default())
} else {
self.slow_offset()
}
}
}
impl Serialize for DateTime {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut buf = SmallFixedBuffer::new();
if self.write_buf(&mut buf, self.opts).is_err() {
err!(SerializeError::DatetimeLibraryUnsupported)
}
serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/uuid.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::buffer::SmallFixedBuffer;
use crate::typeref::INT_ATTR_STR;
use core::ffi::c_uchar;
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct UUID {
ptr: *mut pyo3_ffi::PyObject,
}
impl UUID {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
UUID { ptr: ptr }
}
#[inline(never)]
pub fn write_buf(&self, buf: &mut SmallFixedBuffer) {
let value: u128;
{
// test_uuid_immutable, test_uuid_int
let py_int = ffi!(PyObject_GetAttr(self.ptr, INT_ATTR_STR));
ffi!(Py_DECREF(py_int));
let buffer: [c_uchar; 16] = [0; 16];
unsafe {
// test_uuid_overflow
pyo3_ffi::_PyLong_AsByteArray(
py_int as *mut pyo3_ffi::PyLongObject,
buffer.as_ptr() as *mut c_uchar,
16,
1, // little_endian
0, // is_signed
)
};
value = u128::from_le_bytes(buffer);
}
unsafe {
debug_assert!(buf.len() == 0);
let len = uuid::Uuid::from_u128(value)
.hyphenated()
.encode_lower(buf.as_mut_slice())
.len();
buf.set_written(len);
debug_assert!(buf.len() == len);
}
}
}
impl Serialize for UUID {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut buf = SmallFixedBuffer::new();
self.write_buf(&mut buf);
serializer.serialize_unit_struct(str_from_slice!(buf.as_ptr(), buf.len()))
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/unicode.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::error::SerializeError;
use crate::str::{unicode_to_str, unicode_to_str_via_ffi};
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct StrSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl StrSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
StrSerializer { ptr: ptr }
}
}
impl Serialize for StrSerializer {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let uni = {
let tmp = unicode_to_str(self.ptr);
if unlikely!(tmp.is_none()) {
err!(SerializeError::InvalidStr)
};
tmp.unwrap()
};
serializer.serialize_str(uni)
}
}
#[repr(transparent)]
pub struct StrSubclassSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl StrSubclassSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
StrSubclassSerializer { ptr: ptr }
}
}
impl Serialize for StrSubclassSerializer {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let uni = unicode_to_str_via_ffi(self.ptr);
if unlikely!(uni.is_none()) {
err!(SerializeError::InvalidStr)
}
serializer.serialize_str(uni.unwrap())
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/none.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use serde::ser::{Serialize, Serializer};
pub struct NoneSerializer;
impl NoneSerializer {
pub const fn new() -> Self {
Self {}
}
}
impl Serialize for NoneSerializer {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_unit()
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/dataclass.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::error::SerializeError;
use crate::serialize::per_type::dict::ZeroDictSerializer;
use crate::serialize::serializer::PyObjectSerializer;
use crate::serialize::state::SerializerState;
use crate::str::unicode_to_str;
use crate::typeref::{
DATACLASS_FIELDS_STR, DICT_STR, FIELD_TYPE, FIELD_TYPE_STR, SLOTS_STR, STR_TYPE,
};
use serde::ser::{Serialize, SerializeMap, Serializer};
use core::ptr::NonNull;
#[repr(transparent)]
pub struct DataclassGenericSerializer<'a> {
previous: &'a PyObjectSerializer,
}
impl<'a> DataclassGenericSerializer<'a> {
pub fn new(previous: &'a PyObjectSerializer) -> Self {
Self { previous: previous }
}
}
impl<'a> Serialize for DataclassGenericSerializer<'a> {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if unlikely!(self.previous.state.recursion_limit()) {
err!(SerializeError::RecursionLimit)
}
let dict = ffi!(PyObject_GetAttr(self.previous.ptr, DICT_STR));
let ob_type = ob_type!(self.previous.ptr);
if unlikely!(dict.is_null()) {
ffi!(PyErr_Clear());
DataclassFallbackSerializer::new(
self.previous.ptr,
self.previous.state,
self.previous.default,
)
.serialize(serializer)
} else if pydict_contains!(ob_type, SLOTS_STR) {
let ret = DataclassFallbackSerializer::new(
self.previous.ptr,
self.previous.state,
self.previous.default,
)
.serialize(serializer);
ffi!(Py_DECREF(dict));
ret
} else {
let ret =
DataclassFastSerializer::new(dict, self.previous.state, self.previous.default)
.serialize(serializer);
ffi!(Py_DECREF(dict));
ret
}
}
}
pub struct DataclassFastSerializer {
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl DataclassFastSerializer {
pub fn new(
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
DataclassFastSerializer {
ptr: ptr,
state: state.copy_for_recursive_call(),
default: default,
}
}
}
impl Serialize for DataclassFastSerializer {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let len = ffi!(Py_SIZE(self.ptr)) as usize;
if unlikely!(len == 0) {
return ZeroDictSerializer::new().serialize(serializer);
}
let mut map = serializer.serialize_map(None).unwrap();
let mut pos = 0;
let mut next_key: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
let mut next_value: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
for _ in 0..ffi!(Py_SIZE(self.ptr)) as usize {
let key = next_key;
let value = next_value;
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
let key_as_str = {
let key_ob_type = ob_type!(key);
if unlikely!(!is_class_by_type!(key_ob_type, STR_TYPE)) {
err!(SerializeError::KeyMustBeStr)
}
let tmp = unicode_to_str(key);
if unlikely!(tmp.is_none()) {
err!(SerializeError::InvalidStr)
};
tmp.unwrap()
};
if unlikely!(key_as_str.as_bytes()[0] == b'_') {
continue;
}
let pyvalue = PyObjectSerializer::new(value, self.state, self.default);
map.serialize_key(key_as_str).unwrap();
map.serialize_value(&pyvalue)?;
}
map.end()
}
}
pub struct DataclassFallbackSerializer {
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl DataclassFallbackSerializer {
pub fn new(
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
DataclassFallbackSerializer {
ptr: ptr,
state: state.copy_for_recursive_call(),
default: default,
}
}
}
impl Serialize for DataclassFallbackSerializer {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let fields = ffi!(PyObject_GetAttr(self.ptr, DATACLASS_FIELDS_STR));
debug_assert!(ffi!(Py_REFCNT(fields)) >= 2);
ffi!(Py_DECREF(fields));
let len = ffi!(Py_SIZE(fields)) as usize;
if unlikely!(len == 0) {
return ZeroDictSerializer::new().serialize(serializer);
}
let mut map = serializer.serialize_map(None).unwrap();
let mut pos = 0;
let mut next_key: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
let mut next_value: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
pydict_next!(fields, &mut pos, &mut next_key, &mut next_value);
for _ in 0..ffi!(Py_SIZE(fields)) as usize {
let attr = next_key;
let field = next_value;
pydict_next!(fields, &mut pos, &mut next_key, &mut next_value);
let field_type = ffi!(PyObject_GetAttr(field, FIELD_TYPE_STR));
debug_assert!(ffi!(Py_REFCNT(field_type)) >= 2);
ffi!(Py_DECREF(field_type));
if unsafe { field_type as *mut pyo3_ffi::PyTypeObject != FIELD_TYPE } {
continue;
}
let key_as_str = {
let tmp = unicode_to_str(attr);
if unlikely!(tmp.is_none()) {
err!(SerializeError::InvalidStr)
};
tmp.unwrap()
};
if key_as_str.as_bytes()[0] == b'_' {
continue;
}
let value = ffi!(PyObject_GetAttr(self.ptr, attr));
debug_assert!(ffi!(Py_REFCNT(value)) >= 2);
ffi!(Py_DECREF(value));
let pyvalue = PyObjectSerializer::new(value, self.state, self.default);
map.serialize_key(key_as_str).unwrap();
map.serialize_value(&pyvalue)?
}
map.end()
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/fragment.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::ffi::{Fragment, PyBytes_AS_STRING, PyBytes_GET_SIZE};
use crate::serialize::error::SerializeError;
use crate::str::unicode_to_str;
use crate::typeref::{BYTES_TYPE, STR_TYPE};
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct FragmentSerializer {
ptr: *mut pyo3_ffi::PyObject,
}
impl FragmentSerializer {
pub fn new(ptr: *mut pyo3_ffi::PyObject) -> Self {
FragmentSerializer { ptr: ptr }
}
}
impl Serialize for FragmentSerializer {
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let buffer: &[u8];
unsafe {
let fragment: *mut Fragment = self.ptr as *mut Fragment;
let ob_type = ob_type!((*fragment).contents);
if ob_type == BYTES_TYPE {
buffer = core::slice::from_raw_parts(
PyBytes_AS_STRING((*fragment).contents) as *const u8,
PyBytes_GET_SIZE((*fragment).contents) as usize,
);
} else if ob_type == STR_TYPE {
let uni = unicode_to_str((*fragment).contents);
if unlikely!(uni.is_none()) {
err!(SerializeError::InvalidStr)
}
buffer = uni.unwrap().as_bytes();
} else {
err!(SerializeError::InvalidFragment)
}
}
serializer.serialize_bytes(buffer)
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/dict.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::opt::*;
use crate::serialize::buffer::SmallFixedBuffer;
use crate::serialize::error::SerializeError;
use crate::serialize::obtype::{pyobject_to_obtype, ObType};
use crate::serialize::per_type::datetimelike::DateTimeLike;
use crate::serialize::per_type::{
BoolSerializer, DataclassGenericSerializer, Date, DateTime, DefaultSerializer, EnumSerializer,
FloatSerializer, FragmentSerializer, IntSerializer, ListTupleSerializer, NoneSerializer,
NumpyScalar, NumpySerializer, StrSerializer, StrSubclassSerializer, Time, ZeroListSerializer,
UUID,
};
use crate::serialize::serializer::PyObjectSerializer;
use crate::serialize::state::SerializerState;
use crate::str::{unicode_to_str, unicode_to_str_via_ffi};
use crate::typeref::{STR_TYPE, TRUE, VALUE_STR};
use compact_str::CompactString;
use core::ptr::NonNull;
use serde::ser::{Serialize, SerializeMap, Serializer};
use smallvec::SmallVec;
pub struct ZeroDictSerializer;
impl ZeroDictSerializer {
pub const fn new() -> Self {
Self {}
}
}
impl Serialize for ZeroDictSerializer {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bytes(b"{}")
}
}
pub struct DictGenericSerializer {
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
#[allow(dead_code)]
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl DictGenericSerializer {
pub fn new(
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
) -> Self {
DictGenericSerializer {
ptr: ptr,
state: state.copy_for_recursive_call(),
default: default,
}
}
}
impl Serialize for DictGenericSerializer {
#[inline(always)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if unlikely!(self.state.recursion_limit()) {
err!(SerializeError::RecursionLimit)
}
if unlikely!(ffi!(Py_SIZE(self.ptr)) == 0) {
ZeroDictSerializer::new().serialize(serializer)
} else if likely!(opt_disabled!(self.state.opts(), SORT_OR_NON_STR_KEYS)) {
unsafe {
core::mem::transmute::<&DictGenericSerializer, &Dict>(self).serialize(serializer)
}
} else if opt_enabled!(self.state.opts(), NON_STR_KEYS) {
unsafe {
core::mem::transmute::<&DictGenericSerializer, &DictNonStrKey>(self)
.serialize(serializer)
}
} else {
unsafe {
core::mem::transmute::<&DictGenericSerializer, &DictSortedKey>(self)
.serialize(serializer)
}
}
}
}
macro_rules! impl_serialize_entry {
($map:expr, $self:expr, $key:expr, $value:expr) => {
match pyobject_to_obtype($value, $self.state.opts()) {
ObType::Str => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&StrSerializer::new($value))?;
}
ObType::StrSubclass => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&StrSubclassSerializer::new($value))?;
}
ObType::Int => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&IntSerializer::new($value, $self.state.opts()))?;
}
ObType::None => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&NoneSerializer::new()).unwrap();
}
ObType::Float => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&FloatSerializer::new($value))?;
}
ObType::Bool => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&BoolSerializer::new($value)).unwrap();
}
ObType::Datetime => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&DateTime::new($value, $self.state.opts()))?;
}
ObType::Date => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&Date::new($value))?;
}
ObType::Time => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&Time::new($value, $self.state.opts()))?;
}
ObType::Uuid => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&UUID::new($value)).unwrap();
}
ObType::Dict => {
let pyvalue = DictGenericSerializer::new($value, $self.state, $self.default);
$map.serialize_key($key).unwrap();
$map.serialize_value(&pyvalue)?;
}
ObType::List => {
if ffi!(Py_SIZE($value)) == 0 {
$map.serialize_key($key).unwrap();
$map.serialize_value(&ZeroListSerializer::new()).unwrap();
} else {
let pyvalue =
ListTupleSerializer::from_list($value, $self.state, $self.default);
$map.serialize_key($key).unwrap();
$map.serialize_value(&pyvalue)?;
}
}
ObType::Tuple => {
if ffi!(Py_SIZE($value)) == 0 {
$map.serialize_key($key).unwrap();
$map.serialize_value(&ZeroListSerializer::new()).unwrap();
} else {
let pyvalue =
ListTupleSerializer::from_tuple($value, $self.state, $self.default);
$map.serialize_key($key).unwrap();
$map.serialize_value(&pyvalue)?;
}
}
ObType::Dataclass => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&DataclassGenericSerializer::new(&PyObjectSerializer::new(
$value,
$self.state,
$self.default,
)))?;
}
ObType::Enum => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&EnumSerializer::new(&PyObjectSerializer::new(
$value,
$self.state,
$self.default,
)))?;
}
ObType::NumpyArray => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&NumpySerializer::new(&PyObjectSerializer::new(
$value,
$self.state,
$self.default,
)))?;
}
ObType::NumpyScalar => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&NumpyScalar::new($value, $self.state.opts()))?;
}
ObType::Fragment => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&FragmentSerializer::new($value))?;
}
ObType::Unknown => {
$map.serialize_key($key).unwrap();
$map.serialize_value(&DefaultSerializer::new(&PyObjectSerializer::new(
$value,
$self.state,
$self.default,
)))?;
}
}
};
}
pub struct Dict {
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl Serialize for Dict {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut pos = 0;
let mut next_key: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
let mut next_value: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
let mut map = serializer.serialize_map(None).unwrap();
let len = ffi!(Py_SIZE(self.ptr)) as usize;
assume!(len > 0);
for _ in 0..len {
let key = next_key;
let value = next_value;
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
// key
let key_as_str = {
let key_ob_type = ob_type!(key);
if unlikely!(!is_class_by_type!(key_ob_type, STR_TYPE)) {
err!(SerializeError::KeyMustBeStr)
}
let tmp = unicode_to_str(key);
if unlikely!(tmp.is_none()) {
err!(SerializeError::InvalidStr)
};
tmp.unwrap()
};
// value
impl_serialize_entry!(map, self, key_as_str, value);
}
map.end()
}
}
pub struct DictSortedKey {
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl Serialize for DictSortedKey {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut pos = 0;
let mut next_key: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
let mut next_value: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
let len = ffi!(Py_SIZE(self.ptr)) as usize;
assume!(len > 0);
let mut items: SmallVec<[(&str, *mut pyo3_ffi::PyObject); 8]> =
SmallVec::with_capacity(len);
for _ in 0..len as usize {
let key = next_key;
let value = next_value;
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
if unlikely!(unsafe { ob_type!(key) != STR_TYPE }) {
err!(SerializeError::KeyMustBeStr)
}
let data = unicode_to_str(key);
if unlikely!(data.is_none()) {
err!(SerializeError::InvalidStr)
}
items.push((data.unwrap(), value));
}
items.sort_unstable_by(|a, b| a.0.cmp(b.0));
let mut map = serializer.serialize_map(None).unwrap();
for (key, val) in items.iter() {
let pyvalue = PyObjectSerializer::new(*val, self.state, self.default);
map.serialize_key(key).unwrap();
map.serialize_value(&pyvalue)?;
}
map.end()
}
}
#[inline(never)]
fn non_str_str(key: *mut pyo3_ffi::PyObject) -> Result<CompactString, SerializeError> {
// because of ObType::Enum
let uni = unicode_to_str(key);
if unlikely!(uni.is_none()) {
Err(SerializeError::InvalidStr)
} else {
Ok(CompactString::from(uni.unwrap()))
}
}
#[cold]
#[inline(never)]
fn non_str_str_subclass(key: *mut pyo3_ffi::PyObject) -> Result<CompactString, SerializeError> {
let uni = unicode_to_str_via_ffi(key);
if unlikely!(uni.is_none()) {
Err(SerializeError::InvalidStr)
} else {
Ok(CompactString::from(uni.unwrap()))
}
}
#[inline(never)]
fn non_str_date(key: *mut pyo3_ffi::PyObject) -> Result<CompactString, SerializeError> {
let mut buf = SmallFixedBuffer::new();
Date::new(key).write_buf(&mut buf);
let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());
Ok(CompactString::from(key_as_str))
}
#[inline(never)]
fn non_str_datetime(
key: *mut pyo3_ffi::PyObject,
opts: crate::opt::Opt,
) -> Result<CompactString, SerializeError> {
let mut buf = SmallFixedBuffer::new();
let dt = DateTime::new(key, opts);
if dt.write_buf(&mut buf, opts).is_err() {
return Err(SerializeError::DatetimeLibraryUnsupported);
}
let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());
Ok(CompactString::from(key_as_str))
}
#[cold]
#[inline(never)]
fn non_str_time(
key: *mut pyo3_ffi::PyObject,
opts: crate::opt::Opt,
) -> Result<CompactString, SerializeError> {
let mut buf = SmallFixedBuffer::new();
let time = Time::new(key, opts);
if time.write_buf(&mut buf).is_err() {
return Err(SerializeError::TimeHasTzinfo);
}
let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());
Ok(CompactString::from(key_as_str))
}
#[inline(never)]
fn non_str_uuid(key: *mut pyo3_ffi::PyObject) -> Result<CompactString, SerializeError> {
let mut buf = SmallFixedBuffer::new();
UUID::new(key).write_buf(&mut buf);
let key_as_str = str_from_slice!(buf.as_ptr(), buf.len());
Ok(CompactString::from(key_as_str))
}
#[cold]
#[inline(never)]
fn non_str_float(key: *mut pyo3_ffi::PyObject) -> Result<CompactString, SerializeError> {
let val = ffi!(PyFloat_AS_DOUBLE(key));
if !val.is_finite() {
Ok(CompactString::const_new("null"))
} else {
Ok(CompactString::from(ryu::Buffer::new().format_finite(val)))
}
}
#[inline(never)]
fn non_str_int(key: *mut pyo3_ffi::PyObject) -> Result<CompactString, SerializeError> {
let ival = ffi!(PyLong_AsLongLong(key));
if unlikely!(ival == -1 && !ffi!(PyErr_Occurred()).is_null()) {
ffi!(PyErr_Clear());
let uval = ffi!(PyLong_AsUnsignedLongLong(key));
if unlikely!(uval == u64::MAX && !ffi!(PyErr_Occurred()).is_null()) {
return Err(SerializeError::DictIntegerKey64Bit);
}
Ok(CompactString::from(itoa::Buffer::new().format(uval)))
} else {
Ok(CompactString::from(itoa::Buffer::new().format(ival)))
}
}
#[inline(never)]
fn sort_non_str_dict_items(items: &mut SmallVec<[(CompactString, *mut pyo3_ffi::PyObject); 8]>) {
items.sort_unstable_by(|a, b| a.0.cmp(&b.0));
}
pub struct DictNonStrKey {
ptr: *mut pyo3_ffi::PyObject,
state: SerializerState,
default: Option<NonNull<pyo3_ffi::PyObject>>,
}
impl DictNonStrKey {
fn pyobject_to_string(
key: *mut pyo3_ffi::PyObject,
opts: crate::opt::Opt,
) -> Result<CompactString, SerializeError> {
match pyobject_to_obtype(key, opts) {
ObType::None => Ok(CompactString::const_new("null")),
ObType::Bool => {
if unsafe { key == TRUE } {
Ok(CompactString::const_new("true"))
} else {
Ok(CompactString::const_new("false"))
}
}
ObType::Int => non_str_int(key),
ObType::Float => non_str_float(key),
ObType::Datetime => non_str_datetime(key, opts),
ObType::Date => non_str_date(key),
ObType::Time => non_str_time(key, opts),
ObType::Uuid => non_str_uuid(key),
ObType::Enum => {
let value = ffi!(PyObject_GetAttr(key, VALUE_STR));
debug_assert!(ffi!(Py_REFCNT(value)) >= 2);
let ret = Self::pyobject_to_string(value, opts);
ffi!(Py_DECREF(value));
ret
}
ObType::Str => non_str_str(key),
ObType::StrSubclass => non_str_str_subclass(key),
ObType::Tuple
| ObType::NumpyScalar
| ObType::NumpyArray
| ObType::Dict
| ObType::List
| ObType::Dataclass
| ObType::Fragment
| ObType::Unknown => Err(SerializeError::DictKeyInvalidType),
}
}
}
impl Serialize for DictNonStrKey {
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut pos = 0;
let mut next_key: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
let mut next_value: *mut pyo3_ffi::PyObject = core::ptr::null_mut();
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
let opts = self.state.opts() & NOT_PASSTHROUGH;
let len = ffi!(Py_SIZE(self.ptr)) as usize;
assume!(len > 0);
let mut items: SmallVec<[(CompactString, *mut pyo3_ffi::PyObject); 8]> =
SmallVec::with_capacity(len);
for _ in 0..len {
let key = next_key;
let value = next_value;
pydict_next!(self.ptr, &mut pos, &mut next_key, &mut next_value);
if is_type!(ob_type!(key), STR_TYPE) {
let uni = unicode_to_str(key);
if unlikely!(uni.is_none()) {
err!(SerializeError::InvalidStr)
}
items.push((CompactString::from(uni.unwrap()), value));
} else {
match Self::pyobject_to_string(key, opts) {
Ok(key_as_str) => items.push((key_as_str, value)),
Err(err) => err!(err),
}
}
}
if opt_enabled!(opts, SORT_KEYS) {
sort_non_str_dict_items(&mut items);
}
let mut map = serializer.serialize_map(None).unwrap();
for (key, val) in items.iter() {
let pyvalue = PyObjectSerializer::new(*val, self.state, self.default);
map.serialize_key(key).unwrap();
map.serialize_value(&pyvalue)?;
}
map.end()
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
mod dataclass;
mod datetime;
mod pybool;
#[macro_use]
mod datetimelike;
mod default;
mod dict;
mod float;
mod fragment;
mod int;
mod list;
mod none;
mod numpy;
mod pyenum;
mod unicode;
mod uuid;
pub use dataclass::DataclassGenericSerializer;
pub use datetime::{Date, DateTime, Time};
pub use datetimelike::{DateTimeError, DateTimeLike, Offset};
pub use default::DefaultSerializer;
pub use dict::DictGenericSerializer;
pub use float::FloatSerializer;
pub use fragment::FragmentSerializer;
pub use int::IntSerializer;
pub use list::{ListTupleSerializer, ZeroListSerializer};
pub use none::NoneSerializer;
pub use numpy::{is_numpy_array, is_numpy_scalar, NumpyScalar, NumpySerializer};
pub use pybool::BoolSerializer;
pub use pyenum::EnumSerializer;
pub use unicode::{StrSerializer, StrSubclassSerializer};
pub use uuid::UUID;
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/per_type/default.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use crate::serialize::error::SerializeError;
use crate::serialize::serializer::PyObjectSerializer;
use serde::ser::{Serialize, Serializer};
#[repr(transparent)]
pub struct DefaultSerializer<'a> {
previous: &'a PyObjectSerializer,
}
impl<'a> DefaultSerializer<'a> {
pub fn new(previous: &'a PyObjectSerializer) -> Self {
Self { previous: previous }
}
}
impl<'a> Serialize for DefaultSerializer<'a> {
#[cold]
#[inline(never)]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self.previous.default {
Some(callable) => {
if unlikely!(self.previous.state.default_calls_limit()) {
err!(SerializeError::DefaultRecursionLimit)
}
#[cfg(not(Py_3_10))]
let default_obj = ffi!(PyObject_CallFunctionObjArgs(
callable.as_ptr(),
self.previous.ptr,
core::ptr::null_mut() as *mut pyo3_ffi::PyObject
));
#[cfg(Py_3_10)]
let default_obj = unsafe {
pyo3_ffi::PyObject_Vectorcall(
callable.as_ptr(),
core::ptr::addr_of!(self.previous.ptr),
pyo3_ffi::PyVectorcall_NARGS(1) as usize,
core::ptr::null_mut(),
)
};
if unlikely!(default_obj.is_null()) {
err!(SerializeError::UnsupportedType(nonnull!(self.previous.ptr)))
} else {
let res = PyObjectSerializer::new(
default_obj,
self.previous.state.copy_for_default_call(),
self.previous.default,
)
.serialize(serializer);
ffi!(Py_DECREF(default_obj));
res
}
}
None => err!(SerializeError::UnsupportedType(nonnull!(self.previous.ptr))),
}
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/json.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
// This is an adaptation of `src/value/ser.rs` from serde-json.
use crate::serialize::writer::formatter::{CompactFormatter, Formatter, PrettyFormatter};
use crate::serialize::writer::str::*;
use crate::serialize::writer::WriteExt;
use serde::ser::{self, Impossible, Serialize};
use serde_json::error::{Error, Result};
use std::io;
pub struct Serializer<W, F = CompactFormatter> {
writer: W,
formatter: F,
}
impl<W> Serializer<W>
where
W: io::Write + WriteExt,
{
#[inline]
pub fn new(writer: W) -> Self {
Serializer::with_formatter(writer, CompactFormatter)
}
}
impl<W> Serializer<W, PrettyFormatter>
where
W: io::Write + WriteExt,
{
#[inline]
pub fn pretty(writer: W) -> Self {
Serializer::with_formatter(writer, PrettyFormatter::new())
}
}
impl<W, F> Serializer<W, F>
where
W: io::Write + WriteExt,
F: Formatter,
{
#[inline]
pub fn with_formatter(writer: W, formatter: F) -> Self {
Serializer { writer, formatter }
}
#[inline]
pub fn into_inner(self) -> W {
self.writer
}
}
impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F>
where
W: io::Write + WriteExt,
F: Formatter,
{
type Ok = ();
type Error = Error;
type SerializeSeq = Compound<'a, W, F>;
type SerializeTuple = Impossible<(), Error>;
type SerializeTupleStruct = Impossible<(), Error>;
type SerializeTupleVariant = Impossible<(), Error>;
type SerializeMap = Compound<'a, W, F>;
type SerializeStruct = Impossible<(), Error>;
type SerializeStructVariant = Impossible<(), Error>;
#[inline]
fn serialize_bool(self, value: bool) -> Result<()> {
self.formatter
.write_bool(&mut self.writer, value)
.map_err(Error::io)
}
fn serialize_i8(self, _value: i8) -> Result<()> {
unreachable!();
}
fn serialize_i16(self, _value: i16) -> Result<()> {
unreachable!();
}
#[inline]
fn serialize_i32(self, value: i32) -> Result<()> {
self.formatter
.write_i32(&mut self.writer, value)
.map_err(Error::io)
}
#[inline]
fn serialize_i64(self, value: i64) -> Result<()> {
self.formatter
.write_i64(&mut self.writer, value)
.map_err(Error::io)
}
fn serialize_i128(self, _value: i128) -> Result<()> {
unreachable!();
}
fn serialize_u8(self, _value: u8) -> Result<()> {
unreachable!();
}
fn serialize_u16(self, _value: u16) -> Result<()> {
unreachable!();
}
#[inline]
fn serialize_u32(self, value: u32) -> Result<()> {
self.formatter
.write_u32(&mut self.writer, value)
.map_err(Error::io)
}
#[inline]
fn serialize_u64(self, value: u64) -> Result<()> {
self.formatter
.write_u64(&mut self.writer, value)
.map_err(Error::io)
}
fn serialize_u128(self, _value: u128) -> Result<()> {
unreachable!();
}
#[inline]
fn serialize_f32(self, value: f32) -> Result<()> {
if unlikely!(value.is_infinite() || value.is_nan()) {
self.serialize_unit()
} else {
self.formatter
.write_f32(&mut self.writer, value)
.map_err(Error::io)
}
}
#[inline]
fn serialize_f64(self, value: f64) -> Result<()> {
if unlikely!(value.is_infinite() || value.is_nan()) {
self.serialize_unit()
} else {
self.formatter
.write_f64(&mut self.writer, value)
.map_err(Error::io)
}
}
fn serialize_char(self, _value: char) -> Result<()> {
unreachable!();
}
#[inline(always)]
fn serialize_str(self, value: &str) -> Result<()> {
format_escaped_str(&mut self.writer, value);
Ok(())
}
#[inline(always)]
fn serialize_bytes(self, value: &[u8]) -> Result<()> {
self.writer.reserve(value.len() + 32);
unsafe { self.writer.write_reserved_fragment(value).unwrap() };
Ok(())
}
#[inline]
fn serialize_unit(self) -> Result<()> {
self.formatter
.write_null(&mut self.writer)
.map_err(Error::io)
}
#[inline(always)]
fn serialize_unit_struct(self, name: &'static str) -> Result<()> {
debug_assert!(name.len() <= 36);
reserve_minimum!(self.writer);
unsafe {
self.writer.write_reserved_punctuation(b'"').unwrap();
self.writer
.write_reserved_fragment(name.as_bytes())
.unwrap();
self.writer.write_reserved_punctuation(b'"').unwrap();
}
Ok(())
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<()> {
unreachable!();
}
fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
unreachable!();
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<()>
where
T: ?Sized + Serialize,
{
unreachable!();
}
#[inline]
fn serialize_none(self) -> Result<()> {
self.serialize_unit()
}
#[inline]
fn serialize_some<T>(self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
value.serialize(self)
}
#[inline(always)]
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
self.formatter
.begin_array(&mut self.writer)
.map_err(Error::io)?;
Ok(Compound {
ser: self,
state: State::First,
})
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
unreachable!();
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
unreachable!();
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
unreachable!();
}
#[inline(always)]
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
self.formatter
.begin_object(&mut self.writer)
.map_err(Error::io)?;
Ok(Compound {
ser: self,
state: State::First,
})
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
unreachable!();
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
unreachable!();
}
}
#[derive(Eq, PartialEq)]
pub enum State {
First,
Rest,
}
pub struct Compound<'a, W: 'a, F: 'a> {
ser: &'a mut Serializer<W, F>,
state: State,
}
impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F>
where
W: io::Write + WriteExt,
F: Formatter,
{
type Ok = ();
type Error = Error;
#[inline]
fn serialize_element<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
self.ser
.formatter
.begin_array_value(&mut self.ser.writer, self.state == State::First)
.unwrap();
self.state = State::Rest;
value.serialize(&mut *self.ser)?;
self.ser
.formatter
.end_array_value(&mut self.ser.writer)
.map_err(Error::io)
.unwrap();
Ok(())
}
#[inline]
fn end(self) -> Result<()> {
self.ser.formatter.end_array(&mut self.ser.writer).unwrap();
Ok(())
}
}
impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F>
where
W: io::Write + WriteExt,
F: Formatter,
{
type Ok = ();
type Error = Error;
fn serialize_entry<K, V>(&mut self, _key: &K, _value: &V) -> Result<()>
where
K: ?Sized + Serialize,
V: ?Sized + Serialize,
{
unreachable!()
}
#[inline]
fn serialize_key<T>(&mut self, key: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
self.ser
.formatter
.begin_object_key(&mut self.ser.writer, self.state == State::First)
.unwrap();
self.state = State::Rest;
key.serialize(MapKeySerializer { ser: self.ser })?;
self.ser
.formatter
.end_object_key(&mut self.ser.writer)
.unwrap();
Ok(())
}
#[inline]
fn serialize_value<T>(&mut self, value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
self.ser
.formatter
.begin_object_value(&mut self.ser.writer)
.unwrap();
value.serialize(&mut *self.ser)?;
self.ser
.formatter
.end_object_value(&mut self.ser.writer)
.unwrap();
Ok(())
}
#[inline]
fn end(self) -> Result<()> {
self.ser.formatter.end_object(&mut self.ser.writer).unwrap();
Ok(())
}
}
#[repr(transparent)]
struct MapKeySerializer<'a, W: 'a, F: 'a> {
ser: &'a mut Serializer<W, F>,
}
impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F>
where
W: io::Write + WriteExt,
F: Formatter,
{
type Ok = ();
type Error = Error;
type SerializeSeq = Impossible<(), Error>;
type SerializeTuple = Impossible<(), Error>;
type SerializeTupleStruct = Impossible<(), Error>;
type SerializeTupleVariant = Impossible<(), Error>;
type SerializeMap = Impossible<(), Error>;
type SerializeStruct = Impossible<(), Error>;
type SerializeStructVariant = Impossible<(), Error>;
#[inline(always)]
fn serialize_str(self, value: &str) -> Result<()> {
self.ser.serialize_str(value)
}
fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
) -> Result<()> {
unreachable!();
}
fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
unreachable!();
}
fn serialize_bool(self, _value: bool) -> Result<()> {
unreachable!();
}
fn serialize_i8(self, _value: i8) -> Result<()> {
unreachable!();
}
fn serialize_i16(self, _value: i16) -> Result<()> {
unreachable!();
}
fn serialize_i32(self, _value: i32) -> Result<()> {
unreachable!();
}
fn serialize_i64(self, _value: i64) -> Result<()> {
unreachable!();
}
fn serialize_i128(self, _value: i128) -> Result<()> {
unreachable!();
}
fn serialize_u8(self, _value: u8) -> Result<()> {
unreachable!();
}
fn serialize_u16(self, _value: u16) -> Result<()> {
unreachable!();
}
fn serialize_u32(self, _value: u32) -> Result<()> {
unreachable!();
}
fn serialize_u64(self, _value: u64) -> Result<()> {
unreachable!();
}
fn serialize_u128(self, _value: u128) -> Result<()> {
unreachable!();
}
fn serialize_f32(self, _value: f32) -> Result<()> {
unreachable!();
}
fn serialize_f64(self, _value: f64) -> Result<()> {
unreachable!();
}
fn serialize_char(self, _value: char) -> Result<()> {
unreachable!();
}
fn serialize_bytes(self, _value: &[u8]) -> Result<()> {
unreachable!();
}
fn serialize_unit(self) -> Result<()> {
unreachable!();
}
fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
unreachable!();
}
fn serialize_newtype_variant<T>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<()>
where
T: ?Sized + Serialize,
{
unreachable!();
}
fn serialize_none(self) -> Result<()> {
unreachable!();
}
fn serialize_some<T>(self, _value: &T) -> Result<()>
where
T: ?Sized + Serialize,
{
unreachable!();
}
fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
unreachable!();
}
fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
unreachable!();
}
fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
unreachable!();
}
fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
unreachable!();
}
fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
unreachable!();
}
fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
unreachable!();
}
fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
unreachable!();
}
}
macro_rules! reserve_str {
($writer:expr, $value:expr) => {
$writer.reserve($value.len() * 8 + 32);
};
}
#[cfg(all(feature = "unstable-simd", not(target_arch = "x86_64")))]
#[inline(always)]
fn format_escaped_str<W>(writer: &mut W, value: &str)
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_str!(writer, value);
let written = format_escaped_str_impl_generic_128(
writer.as_mut_buffer_ptr(),
value.as_bytes().as_ptr(),
value.len(),
);
writer.set_written(written);
}
}
#[cfg(all(
feature = "unstable-simd",
target_arch = "x86_64",
not(feature = "avx512")
))]
#[inline(always)]
fn format_escaped_str<W>(writer: &mut W, value: &str)
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_str!(writer, value);
let written = format_escaped_str_impl_sse2_128(
writer.as_mut_buffer_ptr(),
value.as_bytes().as_ptr(),
value.len(),
);
writer.set_written(written);
}
}
#[cfg(all(feature = "unstable-simd", target_arch = "x86_64", feature = "avx512"))]
#[inline(always)]
fn format_escaped_str<W>(writer: &mut W, value: &str)
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_str!(writer, value);
if std::is_x86_feature_detected!("avx512vl") {
let written = format_escaped_str_impl_512vl(
writer.as_mut_buffer_ptr(),
value.as_bytes().as_ptr(),
value.len(),
);
writer.set_written(written);
} else {
let written = format_escaped_str_impl_sse2_128(
writer.as_mut_buffer_ptr(),
value.as_bytes().as_ptr(),
value.len(),
);
writer.set_written(written);
};
}
}
#[cfg(all(not(feature = "unstable-simd"), not(target_arch = "x86_64")))]
#[inline(always)]
fn format_escaped_str<W>(writer: &mut W, value: &str)
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_str!(writer, value);
let written = format_escaped_str_scalar(
writer.as_mut_buffer_ptr(),
value.as_bytes().as_ptr(),
value.len(),
);
writer.set_written(written);
}
}
#[cfg(all(not(feature = "unstable-simd"), target_arch = "x86_64"))]
#[inline(always)]
fn format_escaped_str<W>(writer: &mut W, value: &str)
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_str!(writer, value);
let written = format_escaped_str_impl_sse2_128(
writer.as_mut_buffer_ptr(),
value.as_bytes().as_ptr(),
value.len(),
);
writer.set_written(written);
}
}
#[inline]
pub fn to_writer<W, T>(writer: W, value: &T) -> Result<()>
where
W: io::Write + WriteExt,
T: ?Sized + Serialize,
{
let mut ser = Serializer::new(writer);
value.serialize(&mut ser)
}
#[inline]
pub fn to_writer_pretty<W, T>(writer: W, value: &T) -> Result<()>
where
W: io::Write + WriteExt,
T: ?Sized + Serialize,
{
let mut ser = Serializer::pretty(writer);
value.serialize(&mut ser)
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/formatter.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
// This is an adaptation of `src/value/ser.rs` from serde-json.
use crate::serialize::writer::WriteExt;
use std::io;
macro_rules! debug_assert_has_capacity {
($writer:expr) => {
debug_assert!($writer.has_capacity(4))
};
}
pub trait Formatter {
#[inline]
fn write_null<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
writer.write_reserved_fragment(b"null")
}
}
#[inline]
fn write_bool<W>(&mut self, writer: &mut W, value: bool) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
let s = if value {
b"true" as &[u8]
} else {
b"false" as &[u8]
};
reserve_minimum!(writer);
unsafe { writer.write_reserved_fragment(s) }
}
fn write_i8<W>(&mut self, _writer: &mut W, _value: i8) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
fn write_i16<W>(&mut self, _writer: &mut W, _value: i16) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
#[inline]
fn write_i32<W>(&mut self, writer: &mut W, value: i32) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
let len = itoap::write_to_ptr(writer.as_mut_buffer_ptr(), value);
writer.set_written(len);
}
Ok(())
}
#[inline]
fn write_i64<W>(&mut self, writer: &mut W, value: i64) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
let len = itoap::write_to_ptr(writer.as_mut_buffer_ptr(), value);
writer.set_written(len);
}
Ok(())
}
fn write_i128<W>(&mut self, _writer: &mut W, _value: i128) -> io::Result<()>
where
W: ?Sized + io::Write,
{
unreachable!();
}
fn write_u8<W>(&mut self, _writer: &mut W, _value: u8) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
fn write_u16<W>(&mut self, _writer: &mut W, _value: u16) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
#[inline]
fn write_u32<W>(&mut self, writer: &mut W, value: u32) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
let len = itoap::write_to_ptr(writer.as_mut_buffer_ptr(), value);
writer.set_written(len);
}
Ok(())
}
#[inline]
fn write_u64<W>(&mut self, writer: &mut W, value: u64) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
let len = itoap::write_to_ptr(writer.as_mut_buffer_ptr(), value);
writer.set_written(len);
}
Ok(())
}
fn write_u128<W>(&mut self, _writer: &mut W, _value: u128) -> io::Result<()>
where
W: ?Sized + io::Write,
{
unreachable!();
}
#[inline]
fn write_f32<W>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
let len = ryu::raw::format32(value, writer.as_mut_buffer_ptr());
writer.set_written(len);
}
Ok(())
}
#[inline]
fn write_f64<W>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unsafe {
reserve_minimum!(writer);
let len = ryu::raw::format64(value, writer.as_mut_buffer_ptr());
writer.set_written(len);
}
Ok(())
}
fn write_number_str<W>(&mut self, _writer: &mut W, _value: &str) -> io::Result<()>
where
W: ?Sized + io::Write,
{
unreachable!();
}
#[inline]
fn begin_string<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
#[inline]
fn end_string<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
#[inline]
fn write_string_fragment<W>(&mut self, _writer: &mut W, _fragment: &str) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
unreachable!();
}
#[inline]
fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
reserve_minimum!(writer);
unsafe { writer.write_reserved_punctuation(b'[').unwrap() };
Ok(())
}
#[inline]
fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
debug_assert_has_capacity!(writer);
unsafe { writer.write_reserved_punctuation(b']').unwrap() };
Ok(())
}
#[inline]
fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
debug_assert_has_capacity!(writer);
if !first {
unsafe { writer.write_reserved_punctuation(b',').unwrap() }
}
Ok(())
}
#[inline]
fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
Ok(())
}
#[inline]
fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
reserve_minimum!(writer);
unsafe {
writer.write_reserved_punctuation(b'{').unwrap();
}
Ok(())
}
#[inline]
fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
debug_assert_has_capacity!(writer);
unsafe {
writer.write_reserved_punctuation(b'}').unwrap();
}
Ok(())
}
#[inline]
fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
debug_assert_has_capacity!(writer);
if !first {
unsafe {
writer.write_reserved_punctuation(b',').unwrap();
}
}
Ok(())
}
#[inline]
fn end_object_key<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
Ok(())
}
#[inline]
fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
debug_assert_has_capacity!(writer);
unsafe { writer.write_reserved_punctuation(b':') }
}
#[inline]
fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
Ok(())
}
}
pub struct CompactFormatter;
impl Formatter for CompactFormatter {}
pub struct PrettyFormatter {
current_indent: usize,
has_value: bool,
}
impl PrettyFormatter {
#[allow(clippy::new_without_default)]
pub const fn new() -> Self {
PrettyFormatter {
current_indent: 0,
has_value: false,
}
}
}
impl Formatter for PrettyFormatter {
#[inline]
fn begin_array<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
self.current_indent += 1;
self.has_value = false;
reserve_minimum!(writer);
unsafe { writer.write_reserved_punctuation(b'[') }
}
#[inline]
fn end_array<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
self.current_indent -= 1;
let num_spaces = self.current_indent * 2;
reserve_pretty!(writer, num_spaces);
unsafe {
if self.has_value {
writer.write_reserved_punctuation(b'\n')?;
writer.write_reserved_indent(num_spaces)?;
}
writer.write_reserved_punctuation(b']')
}
}
#[inline]
fn begin_array_value<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
let num_spaces = self.current_indent * 2;
reserve_pretty!(writer, num_spaces);
unsafe {
writer.write_reserved_fragment(if first { b"\n" } else { b",\n" })?;
writer.write_reserved_indent(num_spaces)?;
};
Ok(())
}
#[inline]
fn end_array_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.has_value = true;
Ok(())
}
#[inline]
fn begin_object<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
self.current_indent += 1;
self.has_value = false;
reserve_minimum!(writer);
unsafe { writer.write_reserved_punctuation(b'{') }
}
#[inline]
fn end_object<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
self.current_indent -= 1;
let num_spaces = self.current_indent * 2;
reserve_pretty!(writer, num_spaces);
unsafe {
if self.has_value {
writer.write_reserved_punctuation(b'\n')?;
writer.write_reserved_indent(num_spaces)?;
}
writer.write_reserved_punctuation(b'}')
}
}
#[inline]
fn begin_object_key<W>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
let num_spaces = self.current_indent * 2;
reserve_pretty!(writer, num_spaces);
unsafe {
writer.write_reserved_fragment(if first { b"\n" } else { b",\n" })?;
writer.write_reserved_indent(num_spaces)?;
}
Ok(())
}
#[inline]
fn begin_object_value<W>(&mut self, writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write + WriteExt,
{
reserve_minimum!(writer);
unsafe { writer.write_reserved_fragment(b": ").unwrap() };
Ok(())
}
#[inline]
fn end_object_value<W>(&mut self, _writer: &mut W) -> io::Result<()>
where
W: ?Sized + io::Write,
{
self.has_value = true;
Ok(())
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/byteswriter.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::ffi::c_char;
use core::ptr::NonNull;
use pyo3_ffi::{
PyBytesObject, PyBytes_FromStringAndSize, PyObject, PyVarObject, Py_ssize_t, _PyBytes_Resize,
};
use std::io::Error;
const BUFFER_LENGTH: usize = 1024;
pub struct BytesWriter {
cap: usize,
len: usize,
bytes: *mut PyBytesObject,
}
impl BytesWriter {
pub fn default() -> Self {
BytesWriter {
cap: BUFFER_LENGTH,
len: 0,
bytes: unsafe {
PyBytes_FromStringAndSize(core::ptr::null_mut(), BUFFER_LENGTH as isize)
as *mut PyBytesObject
},
}
}
pub fn bytes_ptr(&mut self) -> NonNull<PyObject> {
unsafe { NonNull::new_unchecked(self.bytes as *mut PyObject) }
}
pub fn finish(&mut self) -> NonNull<PyObject> {
unsafe {
core::ptr::write(self.buffer_ptr(), 0);
(*self.bytes.cast::<PyVarObject>()).ob_size = self.len as Py_ssize_t;
self.resize(self.len);
self.bytes_ptr()
}
}
fn buffer_ptr(&self) -> *mut u8 {
unsafe {
core::mem::transmute::<*mut [c_char; 1], *mut u8>(core::ptr::addr_of_mut!(
(*self.bytes).ob_sval
))
.add(self.len)
}
}
#[inline]
pub fn resize(&mut self, len: usize) {
self.cap = len;
unsafe {
#[allow(clippy::unnecessary_cast)]
_PyBytes_Resize(
core::ptr::addr_of_mut!(self.bytes) as *mut *mut PyBytesObject
as *mut *mut PyObject,
len as isize,
);
}
}
#[cold]
#[inline(never)]
fn grow(&mut self, len: usize) {
let mut cap = self.cap;
while len >= cap {
cap *= 2;
}
self.resize(cap);
}
}
impl std::io::Write for BytesWriter {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
let _ = self.write_all(buf);
Ok(buf.len())
}
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> {
let to_write = buf.len();
let end_length = self.len + to_write;
if unlikely!(end_length >= self.cap) {
self.grow(end_length);
}
unsafe {
core::ptr::copy_nonoverlapping(buf.as_ptr(), self.buffer_ptr(), to_write);
};
self.len = end_length;
Ok(())
}
fn flush(&mut self) -> Result<(), Error> {
Ok(())
}
}
// hack based on saethlin's research and patch in https://github.com/serde-rs/json/issues/766
pub trait WriteExt: std::io::Write {
#[inline]
fn as_mut_buffer_ptr(&mut self) -> *mut u8 {
core::ptr::null_mut()
}
#[inline]
fn reserve(&mut self, len: usize) {
let _ = len;
}
#[inline]
fn has_capacity(&mut self, _len: usize) -> bool {
false
}
#[inline]
fn set_written(&mut self, len: usize) {
let _ = len;
}
#[inline]
fn write_str(&mut self, val: &str) -> Result<(), Error> {
let _ = val;
Ok(())
}
#[inline]
unsafe fn write_reserved_fragment(&mut self, val: &[u8]) -> Result<(), Error> {
let _ = val;
Ok(())
}
#[inline]
unsafe fn write_reserved_punctuation(&mut self, val: u8) -> Result<(), Error> {
let _ = val;
Ok(())
}
#[inline]
unsafe fn write_reserved_indent(&mut self, len: usize) -> Result<(), Error> {
let _ = len;
Ok(())
}
}
impl WriteExt for &mut BytesWriter {
#[inline(always)]
fn as_mut_buffer_ptr(&mut self) -> *mut u8 {
self.buffer_ptr()
}
#[inline(always)]
fn reserve(&mut self, len: usize) {
let end_length = self.len + len;
if unlikely!(end_length >= self.cap) {
self.grow(end_length);
}
}
#[inline]
fn has_capacity(&mut self, len: usize) -> bool {
self.len + len <= self.cap
}
#[inline(always)]
fn set_written(&mut self, len: usize) {
self.len += len;
}
fn write_str(&mut self, val: &str) -> Result<(), Error> {
let to_write = val.len();
let end_length = self.len + to_write + 2;
if unlikely!(end_length >= self.cap) {
self.grow(end_length);
}
unsafe {
let ptr = self.buffer_ptr();
core::ptr::write(ptr, b'"');
core::ptr::copy_nonoverlapping(val.as_ptr(), ptr.add(1), to_write);
core::ptr::write(ptr.add(to_write + 1), b'"');
};
self.len = end_length;
Ok(())
}
unsafe fn write_reserved_fragment(&mut self, val: &[u8]) -> Result<(), Error> {
let to_write = val.len();
unsafe {
core::ptr::copy_nonoverlapping(val.as_ptr(), self.buffer_ptr(), to_write);
};
self.len += to_write;
Ok(())
}
#[inline(always)]
unsafe fn write_reserved_punctuation(&mut self, val: u8) -> Result<(), Error> {
unsafe { core::ptr::write(self.buffer_ptr(), val) };
self.len += 1;
Ok(())
}
#[inline(always)]
unsafe fn write_reserved_indent(&mut self, len: usize) -> Result<(), Error> {
unsafe {
core::ptr::write_bytes(self.buffer_ptr(), b' ', len);
};
self.len += len;
Ok(())
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
mod byteswriter;
mod formatter;
mod json;
mod str;
pub use byteswriter::{BytesWriter, WriteExt};
pub use json::{to_writer, to_writer_pretty};
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/str/avx512.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::mem::transmute;
use super::escape::QUOTE_TAB;
use core::arch::x86_64::{
__m256i, _mm256_cmpeq_epu8_mask, _mm256_cmplt_epu8_mask, _mm256_load_si256, _mm256_loadu_si256,
_mm256_maskz_loadu_epi8, _mm256_storeu_epi8,
};
#[repr(C, align(32))]
struct ConstArray {
pub data: [u8; 32],
}
const BLASH: ConstArray = ConstArray { data: [b'\\'; 32] };
const QUOTE: ConstArray = ConstArray { data: [b'"'; 32] };
const X20: ConstArray = ConstArray { data: [32; 32] };
macro_rules! impl_format_simd_avx512vl {
($dst:expr, $src:expr, $value_len:expr) => {
let mut nb: usize = $value_len;
let blash = _mm256_load_si256(BLASH.data.as_ptr() as *const __m256i);
let quote = _mm256_load_si256(QUOTE.data.as_ptr() as *const __m256i);
let x20 = _mm256_load_si256(X20.data.as_ptr() as *const __m256i);
unsafe {
while nb >= STRIDE {
let str_vec = _mm256_loadu_si256(transmute::<*const u8, *const __m256i>($src));
_mm256_storeu_epi8($dst as *mut i8, str_vec);
let mask = _mm256_cmpeq_epu8_mask(str_vec, blash)
| _mm256_cmpeq_epu8_mask(str_vec, quote)
| _mm256_cmplt_epu8_mask(str_vec, x20);
if unlikely!(mask > 0) {
let cn = trailing_zeros!(mask);
$src = $src.add(cn);
$dst = $dst.add(cn);
nb -= cn;
nb -= 1;
let escape = QUOTE_TAB[*($src) as usize];
$src = $src.add(1);
write_escape!(escape, $dst);
$dst = $dst.add(escape.1 as usize);
} else {
nb -= STRIDE;
$dst = $dst.add(STRIDE);
$src = $src.add(STRIDE);
}
}
if nb > 0 {
loop {
let remainder_mask = !(u32::MAX << nb);
let str_vec = _mm256_maskz_loadu_epi8(remainder_mask, $src as *const i8);
_mm256_storeu_epi8($dst as *mut i8, str_vec);
let mask = (_mm256_cmpeq_epu8_mask(str_vec, blash)
| _mm256_cmpeq_epu8_mask(str_vec, quote)
| _mm256_cmplt_epu8_mask(str_vec, x20))
& remainder_mask;
if unlikely!(mask > 0) {
let cn = trailing_zeros!(mask);
$src = $src.add(cn);
$dst = $dst.add(cn);
nb -= cn;
nb -= 1;
let escape = QUOTE_TAB[*($src) as usize];
$src = $src.add(1);
write_escape!(escape, $dst);
$dst = $dst.add(escape.1 as usize);
} else {
$dst = $dst.add(nb);
break;
}
}
}
}
};
}
#[inline(never)]
#[cfg_attr(
feature = "avx512",
target_feature(enable = "avx512f,avx512bw,avx512vl,bmi2")
)]
pub unsafe fn format_escaped_str_impl_512vl(
odst: *mut u8,
value_ptr: *const u8,
value_len: usize,
) -> usize {
const STRIDE: usize = 32;
let mut dst = odst;
let mut src = value_ptr;
core::ptr::write(dst, b'"');
dst = dst.add(1);
impl_format_simd_avx512vl!(dst, src, value_len);
core::ptr::write(dst, b'"');
dst = dst.add(1);
dst as usize - odst as usize
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/str/generic.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use super::escape::{NEED_ESCAPED, QUOTE_TAB};
use core::simd::cmp::{SimdPartialEq, SimdPartialOrd};
macro_rules! impl_format_simd_generic_128 {
($dst:expr, $src:expr, $value_len:expr) => {
let last_stride_src = $src.add($value_len).sub(STRIDE);
let mut nb: usize = $value_len;
assume!($value_len >= STRIDE);
const BLASH: StrVector = StrVector::from_array([b'\\'; STRIDE]);
const QUOTE: StrVector = StrVector::from_array([b'"'; STRIDE]);
const X20: StrVector = StrVector::from_array([32; STRIDE]);
unsafe {
{
while nb >= STRIDE {
let v = StrVector::from_slice(core::slice::from_raw_parts($src, STRIDE));
let mask =
(v.simd_eq(BLASH) | v.simd_eq(QUOTE) | v.simd_lt(X20)).to_bitmask() as u32;
v.copy_to_slice(core::slice::from_raw_parts_mut($dst, STRIDE));
if unlikely!(mask > 0) {
let cn = trailing_zeros!(mask) as usize;
nb -= cn;
$dst = $dst.add(cn);
$src = $src.add(cn);
nb -= 1;
let escape = QUOTE_TAB[*($src) as usize];
write_escape!(escape, $dst);
$dst = $dst.add(escape.1 as usize);
$src = $src.add(1);
} else {
nb -= STRIDE;
$dst = $dst.add(STRIDE);
$src = $src.add(STRIDE);
}
}
}
if nb > 0 {
let mut scratch: [u8; 32] = [b'a'; 32];
let mut v =
StrVector::from_slice(core::slice::from_raw_parts(last_stride_src, STRIDE));
v.copy_to_slice(core::slice::from_raw_parts_mut(
scratch.as_mut_ptr(),
STRIDE,
));
let mut scratch_ptr = scratch.as_mut_ptr().add(16 - nb);
v = StrVector::from_slice(core::slice::from_raw_parts(scratch_ptr, STRIDE));
let mut mask =
(v.simd_eq(BLASH) | v.simd_eq(QUOTE) | v.simd_lt(X20)).to_bitmask() as u32;
while nb > 0 {
v.copy_to_slice(core::slice::from_raw_parts_mut($dst, STRIDE));
if unlikely!(mask > 0) {
let cn = trailing_zeros!(mask) as usize;
nb -= cn;
$dst = $dst.add(cn);
scratch_ptr = scratch_ptr.add(cn);
nb -= 1;
mask >>= cn + 1;
let escape = QUOTE_TAB[*(scratch_ptr) as usize];
write_escape!(escape, $dst);
$dst = $dst.add(escape.1 as usize);
scratch_ptr = scratch_ptr.add(1);
v = StrVector::from_slice(core::slice::from_raw_parts(scratch_ptr, STRIDE));
} else {
$dst = $dst.add(nb);
break;
}
}
}
}
};
}
#[allow(dead_code)]
#[inline(never)]
#[cfg_attr(target_arch = "x86_64", target_feature(enable = "sse2,bmi1"))]
#[cfg_attr(target_arch = "aarch64", target_feature(enable = "neon"))]
pub unsafe fn format_escaped_str_impl_generic_128(
odst: *mut u8,
value_ptr: *const u8,
value_len: usize,
) -> usize {
const STRIDE: usize = 16;
type StrVector = core::simd::u8x16;
let mut dst = odst;
let mut src = value_ptr;
core::ptr::write(dst, b'"');
dst = dst.add(1);
if value_len < STRIDE {
impl_format_scalar!(dst, src, value_len)
} else {
impl_format_simd_generic_128!(dst, src, value_len);
}
core::ptr::write(dst, b'"');
dst = dst.add(1);
dst as usize - odst as usize
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/str/scalar.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
#[cfg(all(not(feature = "unstable-simd"), not(target_arch = "x86_64")))]
use super::escape::{NEED_ESCAPED, QUOTE_TAB};
macro_rules! impl_format_scalar {
($dst:expr, $src:expr, $value_len:expr) => {
unsafe {
for _ in 0..$value_len {
core::ptr::write($dst, *($src));
$src = $src.add(1);
$dst = $dst.add(1);
if unlikely!(NEED_ESCAPED[*($src.sub(1)) as usize] > 0) {
let escape = QUOTE_TAB[*($src.sub(1)) as usize];
write_escape!(escape, $dst.sub(1));
$dst = $dst.add(escape.1 as usize - 1);
}
}
}
};
}
#[cfg(all(not(feature = "unstable-simd"), not(target_arch = "x86_64")))]
pub unsafe fn format_escaped_str_scalar(
odst: *mut u8,
value_ptr: *const u8,
value_len: usize,
) -> usize {
let mut dst = odst;
let mut src = value_ptr;
core::ptr::write(dst, b'"');
dst = dst.add(1);
impl_format_scalar!(dst, src, value_len);
core::ptr::write(dst, b'"');
dst = dst.add(1);
dst as usize - odst as usize
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/str/sse2.rs | // SPDX-License-Identifier: Apache-2.0
use super::escape::{NEED_ESCAPED, QUOTE_TAB};
use core::mem::transmute;
use core::arch::x86_64::{
__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_or_si128, _mm_set1_epi8,
_mm_setzero_si128, _mm_storeu_si128, _mm_subs_epu8,
};
macro_rules! splat_mm128 {
($val:expr) => {
_mm_set1_epi8(transmute::<u8, i8>($val))
};
}
macro_rules! impl_format_simd_sse2_128 {
($dst:expr, $src:expr, $value_len:expr) => {
let last_stride_src = $src.add($value_len).sub(STRIDE);
let mut nb: usize = $value_len;
assume!($value_len >= STRIDE);
let blash = splat_mm128!(b'\\');
let quote = splat_mm128!(b'"');
let x20 = splat_mm128!(31);
let v0 = _mm_setzero_si128();
unsafe {
while nb >= STRIDE {
let str_vec = _mm_loadu_si128($src as *const __m128i);
let mask = _mm_movemask_epi8(_mm_or_si128(
_mm_or_si128(
_mm_cmpeq_epi8(str_vec, blash),
_mm_cmpeq_epi8(str_vec, quote),
),
_mm_cmpeq_epi8(_mm_subs_epu8(str_vec, x20), v0),
)) as u32;
_mm_storeu_si128($dst as *mut __m128i, str_vec);
if unlikely!(mask > 0) {
let cn = trailing_zeros!(mask) as usize;
nb -= cn;
$dst = $dst.add(cn);
$src = $src.add(cn);
nb -= 1;
let escape = QUOTE_TAB[*($src) as usize];
write_escape!(escape, $dst);
$dst = $dst.add(escape.1 as usize);
$src = $src.add(1);
} else {
nb -= STRIDE;
$dst = $dst.add(STRIDE);
$src = $src.add(STRIDE);
}
}
if nb > 0 {
let mut scratch: [u8; 32] = [b'a'; 32];
let mut str_vec = _mm_loadu_si128(last_stride_src as *const __m128i);
_mm_storeu_si128(scratch.as_mut_ptr() as *mut __m128i, str_vec);
let mut scratch_ptr = scratch.as_mut_ptr().add(16 - nb);
str_vec = _mm_loadu_si128(scratch_ptr as *const __m128i);
let mut mask = _mm_movemask_epi8(_mm_or_si128(
_mm_or_si128(
_mm_cmpeq_epi8(str_vec, blash),
_mm_cmpeq_epi8(str_vec, quote),
),
_mm_cmpeq_epi8(_mm_subs_epu8(str_vec, x20), v0),
)) as u32;
while nb > 0 {
_mm_storeu_si128($dst as *mut __m128i, str_vec);
if unlikely!(mask > 0) {
let cn = trailing_zeros!(mask) as usize;
nb -= cn;
$dst = $dst.add(cn);
scratch_ptr = scratch_ptr.add(cn);
nb -= 1;
mask >>= cn + 1;
let escape = QUOTE_TAB[*(scratch_ptr) as usize];
write_escape!(escape, $dst);
$dst = $dst.add(escape.1 as usize);
scratch_ptr = scratch_ptr.add(1);
str_vec = _mm_loadu_si128(scratch_ptr as *const __m128i);
} else {
$dst = $dst.add(nb);
break;
}
}
}
}
};
}
#[allow(dead_code)]
#[inline(never)]
pub unsafe fn format_escaped_str_impl_sse2_128(
odst: *mut u8,
value_ptr: *const u8,
value_len: usize,
) -> usize {
const STRIDE: usize = 16;
let mut dst = odst;
let mut src = value_ptr;
core::ptr::write(dst, b'"');
dst = dst.add(1);
if value_len < STRIDE {
impl_format_scalar!(dst, src, value_len)
} else {
impl_format_simd_sse2_128!(dst, src, value_len);
}
core::ptr::write(dst, b'"');
dst = dst.add(1);
dst as usize - odst as usize
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/str/escape.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
// the constants and SIMD approach are adapted from cloudwego's sonic-rs
macro_rules! write_escape {
($escape:expr, $dst:expr) => {
core::ptr::copy_nonoverlapping($escape.0.as_ptr(), $dst, 8);
};
}
pub const NEED_ESCAPED: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
pub const QUOTE_TAB: [([u8; 7], u8); 96] = [
(*b"\\u0000\0", 6),
(*b"\\u0001\0", 6),
(*b"\\u0002\0", 6),
(*b"\\u0003\0", 6),
(*b"\\u0004\0", 6),
(*b"\\u0005\0", 6),
(*b"\\u0006\0", 6),
(*b"\\u0007\0", 6),
(*b"\\b\0\0\0\0\0", 2),
(*b"\\t\0\0\0\0\0", 2),
(*b"\\n\0\0\0\0\0", 2),
(*b"\\u000b\0", 6),
(*b"\\f\0\0\0\0\0", 2),
(*b"\\r\0\0\0\0\0", 2),
(*b"\\u000e\0", 6),
(*b"\\u000f\0", 6),
(*b"\\u0010\0", 6),
(*b"\\u0011\0", 6),
(*b"\\u0012\0", 6),
(*b"\\u0013\0", 6),
(*b"\\u0014\0", 6),
(*b"\\u0015\0", 6),
(*b"\\u0016\0", 6),
(*b"\\u0017\0", 6),
(*b"\\u0018\0", 6),
(*b"\\u0019\0", 6),
(*b"\\u001a\0", 6),
(*b"\\u001b\0", 6),
(*b"\\u001c\0", 6),
(*b"\\u001d\0", 6),
(*b"\\u001e\0", 6),
(*b"\\u001f\0", 6),
([0; 7], 0),
([0; 7], 0),
(*b"\\\"\0\0\0\0\0", 2),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
(*b"\\\\\0\0\0\0\0", 2),
([0; 7], 0),
([0; 7], 0),
([0; 7], 0),
];
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer | lc_public_repos/langsmith-sdk/vendor/orjson/src/serialize/writer/str/mod.rs | // SPDX-License-Identifier: Apache-2.0
#[macro_use]
mod escape;
#[macro_use]
mod scalar;
#[cfg(target_arch = "x86_64")]
mod sse2;
#[cfg(all(feature = "unstable-simd", target_arch = "x86_64", feature = "avx512"))]
mod avx512;
#[cfg(feature = "unstable-simd")]
mod generic;
#[cfg(all(not(feature = "unstable-simd"), not(target_arch = "x86_64")))]
pub use scalar::format_escaped_str_scalar;
#[allow(unused_imports)]
#[cfg(feature = "unstable-simd")]
pub use generic::format_escaped_str_impl_generic_128;
#[cfg(all(feature = "unstable-simd", target_arch = "x86_64", feature = "avx512"))]
pub use avx512::format_escaped_str_impl_512vl;
#[allow(unused_imports)]
#[cfg(target_arch = "x86_64")]
pub use sse2::format_escaped_str_impl_sse2_128;
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/ffi/long.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
// longintrepr.h, _longobject, _PyLongValue
#[allow(dead_code)]
#[cfg(Py_3_12)]
#[allow(non_upper_case_globals)]
const SIGN_MASK: usize = 3;
#[cfg(all(Py_3_12, feature = "inline_int"))]
#[allow(non_upper_case_globals)]
const SIGN_ZERO: usize = 1;
#[cfg(all(Py_3_12, feature = "inline_int"))]
#[allow(non_upper_case_globals)]
const NON_SIZE_BITS: usize = 3;
#[cfg(Py_3_12)]
#[repr(C)]
pub struct _PyLongValue {
pub lv_tag: usize,
pub ob_digit: u32,
}
#[cfg(Py_3_12)]
#[repr(C)]
pub struct PyLongObject {
pub ob_base: pyo3_ffi::PyObject,
pub long_value: _PyLongValue,
}
#[allow(dead_code)]
#[cfg(not(Py_3_12))]
#[repr(C)]
pub struct PyLongObject {
pub ob_base: pyo3_ffi::PyVarObject,
pub ob_digit: u32,
}
#[cfg(Py_3_12)]
#[inline(always)]
pub fn pylong_is_unsigned(ptr: *mut pyo3_ffi::PyObject) -> bool {
unsafe { (*(ptr as *mut PyLongObject)).long_value.lv_tag & SIGN_MASK == 0 }
}
#[cfg(not(Py_3_12))]
#[inline(always)]
pub fn pylong_is_unsigned(ptr: *mut pyo3_ffi::PyObject) -> bool {
unsafe { (*(ptr as *mut pyo3_ffi::PyVarObject)).ob_size > 0 }
}
#[cfg(all(Py_3_12, feature = "inline_int"))]
#[inline(always)]
pub fn pylong_fits_in_i32(ptr: *mut pyo3_ffi::PyObject) -> bool {
unsafe { (*(ptr as *mut PyLongObject)).long_value.lv_tag < (2 << NON_SIZE_BITS) }
}
#[cfg(all(not(Py_3_12), feature = "inline_int"))]
#[inline(always)]
pub fn pylong_fits_in_i32(ptr: *mut pyo3_ffi::PyObject) -> bool {
unsafe { isize::abs((*(ptr as *mut pyo3_ffi::PyVarObject)).ob_size) == 1 }
}
#[cfg(all(Py_3_12, feature = "inline_int"))]
#[inline(always)]
pub fn pylong_is_zero(ptr: *mut pyo3_ffi::PyObject) -> bool {
unsafe { (*(ptr as *mut PyLongObject)).long_value.lv_tag & SIGN_MASK == SIGN_ZERO }
}
#[cfg(all(not(Py_3_12), feature = "inline_int"))]
#[inline(always)]
pub fn pylong_is_zero(ptr: *mut pyo3_ffi::PyObject) -> bool {
unsafe { (*(ptr as *mut pyo3_ffi::PyVarObject)).ob_size == 0 }
}
#[cfg(all(Py_3_12, feature = "inline_int"))]
#[inline(always)]
pub fn pylong_get_inline_value(ptr: *mut pyo3_ffi::PyObject) -> i64 {
unsafe {
if pylong_is_unsigned(ptr) {
(*(ptr as *mut PyLongObject)).long_value.ob_digit as i64
} else {
-1 * (*(ptr as *mut PyLongObject)).long_value.ob_digit as i64
}
}
}
#[cfg(all(not(Py_3_12), feature = "inline_int"))]
#[inline(always)]
pub fn pylong_get_inline_value(ptr: *mut pyo3_ffi::PyObject) -> i64 {
unsafe {
(*(ptr as *mut pyo3_ffi::PyVarObject)).ob_size as i64
* (*(ptr as *mut PyLongObject)).ob_digit as i64
}
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/ffi/buffer.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::ffi::c_int;
use pyo3_ffi::*;
#[repr(C)]
pub struct _PyManagedBufferObject {
pub ob_base: *mut pyo3_ffi::PyObject,
pub flags: c_int,
pub exports: Py_ssize_t,
pub master: *mut Py_buffer,
}
#[repr(C)]
pub struct PyMemoryViewObject {
pub ob_base: PyVarObject,
pub mbuf: *mut _PyManagedBufferObject,
pub hash: Py_hash_t,
pub flags: c_int,
pub exports: Py_ssize_t,
pub view: Py_buffer,
pub weakreflist: *mut PyObject,
pub ob_array: [Py_ssize_t; 1],
}
#[allow(non_snake_case)]
#[inline(always)]
pub unsafe fn PyMemoryView_GET_BUFFER(op: *mut PyObject) -> *const Py_buffer {
&(*op.cast::<PyMemoryViewObject>()).view
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/ffi/yyjson.rs | #[repr(C)]
pub struct yyjson_alc {
pub malloc: ::core::option::Option<
unsafe extern "C" fn(
ctx: *mut ::core::ffi::c_void,
size: usize,
) -> *mut ::core::ffi::c_void,
>,
pub realloc: ::core::option::Option<
unsafe extern "C" fn(
ctx: *mut ::core::ffi::c_void,
ptr: *mut ::core::ffi::c_void,
size: usize,
) -> *mut ::core::ffi::c_void,
>,
pub free: ::core::option::Option<
unsafe extern "C" fn(ctx: *mut ::core::ffi::c_void, ptr: *mut ::core::ffi::c_void),
>,
pub ctx: *mut ::core::ffi::c_void,
}
extern "C" {
pub fn yyjson_alc_pool_init(
alc: *mut yyjson_alc,
buf: *mut ::core::ffi::c_void,
size: usize,
) -> bool;
}
pub type yyjson_read_code = u32;
pub const YYJSON_READ_SUCCESS: yyjson_read_code = 0;
#[repr(C)]
pub struct yyjson_read_err {
pub code: yyjson_read_code,
pub msg: *const ::core::ffi::c_char,
pub pos: usize,
}
extern "C" {
pub fn yyjson_read_opts(
dat: *mut ::core::ffi::c_char,
len: usize,
alc: *const yyjson_alc,
err: *mut yyjson_read_err,
) -> *mut yyjson_doc;
}
extern "C" {
pub fn yyjson_doc_free(doc: *mut yyjson_doc);
}
#[repr(C)]
pub union yyjson_val_uni {
pub u64_: u64,
pub i64_: i64,
pub f64_: f64,
pub str_: *const ::core::ffi::c_char,
pub ptr: *mut ::core::ffi::c_void,
pub ofs: usize,
}
#[repr(C)]
pub struct yyjson_val {
pub tag: u64,
pub uni: yyjson_val_uni,
}
#[repr(C)]
pub struct yyjson_doc {
pub root: *mut yyjson_val,
pub alc: yyjson_alc,
pub dat_read: usize,
pub val_read: usize,
pub str_pool: *mut ::core::ffi::c_char,
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/ffi/bytes.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::ffi::c_char;
use pyo3_ffi::{PyBytesObject, PyObject, PyVarObject, Py_ssize_t};
#[allow(non_snake_case)]
#[inline(always)]
pub unsafe fn PyBytes_AS_STRING(op: *mut PyObject) -> *const c_char {
&(*op.cast::<PyBytesObject>()).ob_sval as *const c_char
}
#[allow(non_snake_case)]
#[inline(always)]
pub unsafe fn PyBytes_GET_SIZE(op: *mut PyObject) -> Py_ssize_t {
(*op.cast::<PyVarObject>()).ob_size
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/ffi/fragment.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
use core::ffi::{c_char, c_ulong};
use core::ptr::null_mut;
use pyo3_ffi::*;
// https://docs.python.org/3/c-api/typeobj.html#typedef-examples
#[repr(C)]
pub struct Fragment {
pub ob_refcnt: pyo3_ffi::Py_ssize_t,
pub ob_type: *mut pyo3_ffi::PyTypeObject,
pub contents: *mut pyo3_ffi::PyObject,
}
#[cold]
#[inline(never)]
#[cfg_attr(feature = "optimize", optimize(size))]
fn raise_args_exception() -> *mut PyObject {
unsafe {
let msg = "orjson.Fragment() takes exactly 1 positional argument";
let err_msg =
PyUnicode_FromStringAndSize(msg.as_ptr() as *const c_char, msg.len() as isize);
PyErr_SetObject(PyExc_TypeError, err_msg);
Py_DECREF(err_msg);
};
null_mut()
}
#[no_mangle]
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub unsafe extern "C" fn orjson_fragment_tp_new(
_subtype: *mut PyTypeObject,
args: *mut PyObject,
kwds: *mut PyObject,
) -> *mut PyObject {
if Py_SIZE(args) != 1 || !kwds.is_null() {
raise_args_exception();
null_mut()
} else {
let contents = PyTuple_GET_ITEM(args, 0);
Py_INCREF(contents);
let obj = Box::new(Fragment {
ob_refcnt: 1,
ob_type: crate::typeref::FRAGMENT_TYPE,
contents: contents,
});
Box::into_raw(obj) as *mut PyObject
}
}
#[no_mangle]
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub unsafe extern "C" fn orjson_fragment_dealloc(object: *mut PyObject) {
Py_DECREF((*(object as *mut Fragment)).contents);
std::alloc::dealloc(object as *mut u8, std::alloc::Layout::new::<Fragment>());
}
#[cfg(Py_3_10)]
const FRAGMENT_TP_FLAGS: c_ulong = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE;
#[cfg(not(Py_3_10))]
const FRAGMENT_TP_FLAGS: c_ulong = Py_TPFLAGS_DEFAULT;
#[no_mangle]
#[cold]
#[cfg_attr(feature = "optimize", optimize(size))]
pub unsafe extern "C" fn orjson_fragmenttype_new() -> *mut PyTypeObject {
let ob = Box::new(PyTypeObject {
ob_base: PyVarObject {
ob_base: PyObject {
#[cfg(Py_3_12)]
ob_refcnt: pyo3_ffi::PyObjectObRefcnt { ob_refcnt: 0 },
#[cfg(not(Py_3_12))]
ob_refcnt: 0,
ob_type: core::ptr::addr_of_mut!(PyType_Type),
},
ob_size: 0,
},
tp_name: "orjson.Fragment\0".as_ptr() as *const c_char,
tp_basicsize: core::mem::size_of::<Fragment>() as isize,
tp_itemsize: 0,
tp_dealloc: Some(orjson_fragment_dealloc),
tp_init: None,
tp_new: Some(orjson_fragment_tp_new),
tp_flags: FRAGMENT_TP_FLAGS,
// ...
tp_bases: null_mut(),
tp_cache: null_mut(),
tp_del: None,
tp_finalize: None,
tp_free: None,
tp_is_gc: None,
tp_mro: null_mut(),
tp_subclasses: null_mut(),
tp_vectorcall: None,
tp_version_tag: 0,
tp_weaklist: null_mut(),
#[cfg(not(Py_3_9))]
tp_print: None,
tp_vectorcall_offset: 0,
tp_getattr: None,
tp_setattr: None,
tp_as_async: null_mut(),
tp_repr: None,
tp_as_number: null_mut(),
tp_as_sequence: null_mut(),
tp_as_mapping: null_mut(),
tp_hash: None,
tp_call: None,
tp_str: None,
tp_getattro: None,
tp_setattro: None,
tp_as_buffer: null_mut(),
tp_doc: core::ptr::null_mut(),
tp_traverse: None,
tp_clear: None,
tp_richcompare: None,
tp_weaklistoffset: 0,
tp_iter: None,
tp_iternext: None,
tp_methods: null_mut(),
tp_members: null_mut(),
tp_getset: null_mut(),
tp_base: null_mut(),
tp_dict: null_mut(),
tp_descr_get: None,
tp_descr_set: None,
tp_dictoffset: 0,
tp_alloc: None,
#[cfg(Py_3_12)]
tp_watched: 0,
});
let ob_ptr = Box::into_raw(ob);
PyType_Ready(ob_ptr);
ob_ptr
}
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/src | lc_public_repos/langsmith-sdk/vendor/orjson/src/ffi/mod.rs | // SPDX-License-Identifier: (Apache-2.0 OR MIT)
mod buffer;
mod bytes;
mod fragment;
mod long;
#[cfg(feature = "yyjson")]
pub mod yyjson;
pub use buffer::*;
pub use bytes::*;
pub use fragment::{orjson_fragmenttype_new, Fragment};
pub use long::pylong_is_unsigned;
#[cfg(feature = "inline_int")]
pub use long::{pylong_fits_in_i32, pylong_get_inline_value, pylong_is_zero};
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/pysrc | lc_public_repos/langsmith-sdk/vendor/orjson/pysrc/orjson/__init__.pyi | import json
from typing import Any, Callable, Optional, Union
__version__: str
def dumps(
__obj: Any,
default: Optional[Callable[[Any], Any]] = ...,
option: Optional[int] = ...,
) -> bytes: ...
def loads(__obj: Union[bytes, bytearray, memoryview, str]) -> Any: ...
class JSONDecodeError(json.JSONDecodeError): ...
class JSONEncodeError(TypeError): ...
class Fragment(tuple):
contents: Union[bytes, str]
OPT_APPEND_NEWLINE: int
OPT_INDENT_2: int
OPT_NAIVE_UTC: int
OPT_NON_STR_KEYS: int
OPT_OMIT_MICROSECONDS: int
OPT_PASSTHROUGH_DATACLASS: int
OPT_PASSTHROUGH_DATETIME: int
OPT_PASSTHROUGH_SUBCLASS: int
OPT_SERIALIZE_DATACLASS: int
OPT_SERIALIZE_NUMPY: int
OPT_SERIALIZE_UUID: int
OPT_SORT_KEYS: int
OPT_STRICT_INTEGER: int
OPT_UTC_Z: int
|
0 | lc_public_repos/langsmith-sdk/vendor/orjson/pysrc | lc_public_repos/langsmith-sdk/vendor/orjson/pysrc/orjson/__init__.py | # SPDX-License-Identifier: (Apache-2.0 OR MIT)
from .orjson import *
from .orjson import __version__
__all__ = (
"__version__",
"dumps",
"Fragment",
"JSONDecodeError",
"JSONEncodeError",
"loads",
"OPT_APPEND_NEWLINE",
"OPT_INDENT_2",
"OPT_NAIVE_UTC",
"OPT_NON_STR_KEYS",
"OPT_OMIT_MICROSECONDS",
"OPT_PASSTHROUGH_DATACLASS",
"OPT_PASSTHROUGH_DATETIME",
"OPT_PASSTHROUGH_SUBCLASS",
"OPT_SERIALIZE_DATACLASS",
"OPT_SERIALIZE_NUMPY",
"OPT_SERIALIZE_UUID",
"OPT_SORT_KEYS",
"OPT_STRICT_INTEGER",
"OPT_UTC_Z",
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.