1#![cfg_attr(not(any(test, feature = "std")), no_std)]
21
22extern crate alloc;
23
24#[cfg(feature = "disable_panic")]
25extern crate osal_rs;
26
27#[cfg(feature = "disable_panic")]
28extern crate osal_rs_serde;
29
30pub(crate) mod cjson_ffi;
31mod cjson;
32
33pub(crate) mod cjson_utils_ffi;
34mod cjson_utils;
35
36#[cfg(feature = "osal_rs")]
37pub mod ser;
38
39#[cfg(feature = "osal_rs")]
40pub mod de;
41
42pub use cjson::{CJson, CJsonRef, CJsonResult, CJsonError};
44pub use cjson_utils::{JsonPointer, JsonPatch, JsonMergePatch, JsonUtils};
45#[cfg(feature = "osal_rs")]
46use osal_rs_serde::{Deserialize, Result, Serialize};
47
48#[cfg(feature = "osal_rs")]
49use alloc::string::String;
50
51
52
53#[cfg(all(not(any(test, feature = "std")), not(feature = "disable_panic")))]
55use core::alloc::Layout;
56
57#[cfg(all(not(any(test, feature = "std")), not(feature = "disable_panic")))]
58struct CJsonAllocator;
59
60#[cfg(all(not(any(test, feature = "std")), not(feature = "disable_panic")))]
61unsafe impl core::alloc::GlobalAlloc for CJsonAllocator {
62 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
63 unsafe extern "C" {
64 fn malloc(size: usize) -> *mut u8;
65 }
66 unsafe { malloc(layout.size()) }
67 }
68
69 unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
70 unsafe extern "C" {
71 fn free(ptr: *mut u8);
72 }
73 unsafe { free(ptr) }
74 }
75}
76
77#[cfg(all(not(any(test, feature = "std")), not(feature = "disable_panic")))]
78#[global_allocator]
79static ALLOCATOR: CJsonAllocator = CJsonAllocator;
80
81#[cfg(all(not(any(test, feature = "std")), not(feature = "disable_panic")))]
83#[panic_handler]
84fn panic(_info: &core::panic::PanicInfo) -> ! {
85 loop {}
86}
87
88const APP_TAG: &str = "cJSON-RS";
89
90#[cfg(feature = "osal_rs")]
91pub fn to_json<T>(value: &T) -> Result<String>
92where
93 T: Serialize
94{
95 use crate::ser::JsonSerializer;
96 use osal_rs::log_error;
97
98
99 let mut serializer = JsonSerializer::new();
100
101 value.serialize("", &mut serializer).map_err(|e| {
102 log_error!(APP_TAG, "Serialization error: {}", e);
103 osal_rs_serde::Error::InvalidData
104 })?;
105
106 let json = serializer.print_unformatted().map_err(|e| {
107 log_error!(APP_TAG, "Failed to print JSON: {}", e);
108 osal_rs_serde::Error::InvalidData
109 })?;
110
111 Ok(json)
112}
113
114#[cfg(feature = "osal_rs")]
115pub fn from_json<T>(json: &String) -> Result<T>
116where
117 T: Deserialize + Default
118{
119 use crate::de::JsonDeserializer;
120 use osal_rs::log_error;
121
122 let mut deserializer = JsonDeserializer::parse(json).map_err(|e| {
123 log_error!(APP_TAG, "Failed to parse JSON: {}", e);
124 osal_rs_serde::Error::InvalidData
125 })?;
126
127 let ret = T::deserialize(&mut deserializer, "").map_err(|e| {
128 log_error!(APP_TAG, "Failed to deserialize JSON: {}", e);
129 osal_rs_serde::Error::InvalidData
130 })?;
131
132 deserializer.drop();
133
134 Ok(ret)
135}
136