cjson-bindings 0.6.4

Safe Rust bindings for the cJSON library - a lightweight JSON parser in C with support for JSON Pointer (RFC6901), JSON Patch (RFC6902), and JSON Merge Patch (RFC7386)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/***************************************************************************
 *
 * cJSON FFI BINDING FOR RUST
 * Copyright (C) 2026 Antonio Salsi <passy.linux@zresa.it>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, see <https://www.gnu.org/licenses/>.
 *
 ***************************************************************************/

//! Safe Rust wrappers for cJSON_Utils library
//!
//! This module provides safe, idiomatic Rust interfaces over the cJSON_Utils C library,
//! which implements RFC6901 (JSON Pointer), RFC6902 (JSON Patch), and RFC7386 (JSON Merge Patch).

extern crate alloc;

use alloc::ffi::CString;
use alloc::string::String;
use core::ffi::{CStr, c_char};

use crate::cjson::{CJson, CJsonError, CJsonResult};
use crate::cjson_ffi::cJSON;
use crate::cjson_utils_ffi::*;

/// JSON Pointer utilities (RFC6901)
pub struct JsonPointer;

impl JsonPointer {
    /// Get a value from a JSON object using RFC6901 JSON Pointer syntax.
    /// 
    /// # Arguments
    /// * `object` - The JSON object to search in
    /// * `pointer` - The JSON Pointer string (e.g., "/foo/bar/0")
    /// 
    /// # Returns
    /// A borrowed reference to the found item, or NotFound error
    pub fn get(object: &CJson, pointer: &str) -> CJsonResult<CJsonRef> {
        let c_pointer = CString::new(pointer).map_err(|_| CJsonError::InvalidUtf8)?;
        let ptr = unsafe {
            cJSONUtils_GetPointer(object.as_ptr() as *mut cJSON, c_pointer.as_ptr() as *const i8)
        };
        unsafe { CJsonRef::from_ptr(ptr) }.map_err(|_| CJsonError::NotFound)
    }

    /// Get a value from a JSON object using RFC6901 JSON Pointer syntax (case-sensitive).
    /// 
    /// # Arguments
    /// * `object` - The JSON object to search in
    /// * `pointer` - The JSON Pointer string (e.g., "/foo/bar/0")
    /// 
    /// # Returns
    /// A borrowed reference to the found item, or NotFound error
    pub fn get_case_sensitive(object: &CJson, pointer: &str) -> CJsonResult<CJsonRef> {
        let c_pointer = CString::new(pointer).map_err(|_| CJsonError::InvalidUtf8)?;
        let ptr = unsafe {
            cJSONUtils_GetPointerCaseSensitive(
                object.as_ptr() as *mut cJSON,
                c_pointer.as_ptr() as *const i8,
            )
        };
        unsafe { CJsonRef::from_ptr(ptr) }.map_err(|_| CJsonError::NotFound)
    }

    /// Find a JSON Pointer path from one object to a target value within it.
    /// 
    /// # Arguments
    /// * `object` - The JSON object to search in
    /// * `target` - The target value to find
    /// 
    /// # Returns
    /// The JSON Pointer path as a String, or NotFound error
    pub fn find_from_object_to(object: &CJson, target: &CJson) -> CJsonResult<String> {
        let ptr = unsafe {
            cJSONUtils_FindPointerFromObjectTo(object.as_ptr(), target.as_ptr())
        };
        if ptr.is_null() {
            return Err(CJsonError::NotFound);
        }
        let path = unsafe { CStr::from_ptr(ptr as *const c_char).to_string_lossy().into_owned() };
        unsafe { crate::cjson_ffi::cJSON_free(ptr as *mut core::ffi::c_void) };
        Ok(path)
    }
}

/// JSON Patch utilities (RFC6902)
pub struct JsonPatch;

impl JsonPatch {
    /// Generate a JSON Patch (RFC6902) to transform 'from' into 'to'.
    /// 
    /// Note: This function modifies both 'from' and 'to' by sorting their keys.
    /// 
    /// # Arguments
    /// * `from` - The original JSON object
    /// * `to` - The target JSON object
    /// 
    /// # Returns
    /// A new CJson object containing the patch operations
    pub fn generate(from: &mut CJson, to: &mut CJson) -> CJsonResult<CJson> {
        let ptr = unsafe {
            cJSONUtils_GeneratePatches(from.as_mut_ptr(), to.as_mut_ptr())
        };
        unsafe { CJson::from_ptr(ptr) }
    }

    /// Generate a JSON Patch (RFC6902) to transform 'from' into 'to' (case-sensitive).
    /// 
    /// Note: This function modifies both 'from' and 'to' by sorting their keys.
    /// 
    /// # Arguments
    /// * `from` - The original JSON object
    /// * `to` - The target JSON object
    /// 
    /// # Returns
    /// A new CJson object containing the patch operations
    pub fn generate_case_sensitive(from: &mut CJson, to: &mut CJson) -> CJsonResult<CJson> {
        let ptr = unsafe {
            cJSONUtils_GeneratePatchesCaseSensitive(from.as_mut_ptr(), to.as_mut_ptr())
        };
        unsafe { CJson::from_ptr(ptr) }
    }

    /// Apply a JSON Patch (RFC6902) to an object.
    /// 
    /// # Arguments
    /// * `object` - The JSON object to patch
    /// * `patches` - The patch operations to apply
    /// 
    /// # Returns
    /// Ok(()) on success, or an error
    pub fn apply(object: &mut CJson, patches: &CJson) -> CJsonResult<()> {
        let result = unsafe {
            cJSONUtils_ApplyPatches(object.as_mut_ptr(), patches.as_ptr())
        };
        if result == 0 {
            Ok(())
        } else {
            Err(CJsonError::InvalidOperation)
        }
    }

    /// Apply a JSON Patch (RFC6902) to an object (case-sensitive).
    /// 
    /// # Arguments
    /// * `object` - The JSON object to patch
    /// * `patches` - The patch operations to apply
    /// 
    /// # Returns
    /// Ok(()) on success, or an error
    pub fn apply_case_sensitive(object: &mut CJson, patches: &CJson) -> CJsonResult<()> {
        let result = unsafe {
            cJSONUtils_ApplyPatchesCaseSensitive(object.as_mut_ptr(), patches.as_ptr())
        };
        if result == 0 {
            Ok(())
        } else {
            Err(CJsonError::InvalidOperation)
        }
    }

    /// Add a patch operation to a patches array.
    /// 
    /// # Arguments
    /// * `array` - The array of patch operations
    /// * `operation` - The operation type ("add", "remove", "replace", "move", "copy", "test")
    /// * `path` - The JSON Pointer path
    /// * `value` - The value for the operation (optional for some operations)
    pub fn add_to_array(
        array: &mut CJson,
        operation: &str,
        path: &str,
        value: Option<&CJson>,
    ) -> CJsonResult<()> {
        if !array.is_array() {
            return Err(CJsonError::TypeError);
        }

        let c_operation = CString::new(operation).map_err(|_| CJsonError::InvalidUtf8)?;
        let c_path = CString::new(path).map_err(|_| CJsonError::InvalidUtf8)?;

        let value_ptr = value.map(|v| v.as_ptr()).unwrap_or(core::ptr::null());

        unsafe {
            cJSONUtils_AddPatchToArray(
                array.as_mut_ptr(),
                c_operation.as_ptr() as *const i8,
                c_path.as_ptr() as *const i8,
                value_ptr,
            );
        }
        Ok(())
    }
}

/// JSON Merge Patch utilities (RFC7386)
pub struct JsonMergePatch;

impl JsonMergePatch {
    /// Apply a JSON Merge Patch (RFC7386) to a target object.
    /// 
    /// # Arguments
    /// * `target` - The JSON object to merge into
    /// * `patch` - The merge patch to apply
    /// 
    /// # Returns
    /// A new CJson object with the merged result
    pub fn apply(target: &mut CJson, patch: &CJson) -> CJsonResult<CJson> {
        let ptr = unsafe {
            cJSONUtils_MergePatch(target.as_mut_ptr(), patch.as_ptr())
        };
        unsafe { CJson::from_ptr(ptr) }
    }

    /// Apply a JSON Merge Patch (RFC7386) to a target object (case-sensitive).
    /// 
    /// # Arguments
    /// * `target` - The JSON object to merge into
    /// * `patch` - The merge patch to apply
    /// 
    /// # Returns
    /// A new CJson object with the merged result
    pub fn apply_case_sensitive(target: &mut CJson, patch: &CJson) -> CJsonResult<CJson> {
        let ptr = unsafe {
            cJSONUtils_MergePatchCaseSensitive(target.as_mut_ptr(), patch.as_ptr())
        };
        unsafe { CJson::from_ptr(ptr) }
    }

    /// Generate a JSON Merge Patch to transform 'from' into 'to'.
    /// 
    /// Note: This function modifies both 'from' and 'to' by sorting their keys.
    /// 
    /// # Arguments
    /// * `from` - The original JSON object
    /// * `to` - The target JSON object
    /// 
    /// # Returns
    /// A new CJson object containing the merge patch
    pub fn generate(from: &mut CJson, to: &mut CJson) -> CJsonResult<CJson> {
        let ptr = unsafe {
            cJSONUtils_GenerateMergePatch(from.as_mut_ptr(), to.as_mut_ptr())
        };
        unsafe { CJson::from_ptr(ptr) }
    }

    /// Generate a JSON Merge Patch to transform 'from' into 'to' (case-sensitive).
    /// 
    /// Note: This function modifies both 'from' and 'to' by sorting their keys.
    /// 
    /// # Arguments
    /// * `from` - The original JSON object
    /// * `to` - The target JSON object
    /// 
    /// # Returns
    /// A new CJson object containing the merge patch
    pub fn generate_case_sensitive(from: &mut CJson, to: &mut CJson) -> CJsonResult<CJson> {
        let ptr = unsafe {
            cJSONUtils_GenerateMergePatchCaseSensitive(from.as_mut_ptr(), to.as_mut_ptr())
        };
        unsafe { CJson::from_ptr(ptr) }
    }
}

/// Utility functions for JSON object manipulation
pub struct JsonUtils;

impl JsonUtils {
    /// Sort object members alphabetically (case-insensitive).
    /// 
    /// # Arguments
    /// * `object` - The JSON object to sort
    pub fn sort_object(object: &mut CJson) -> CJsonResult<()> {
        if !object.is_object() {
            return Err(CJsonError::TypeError);
        }
        unsafe { cJSONUtils_SortObject(object.as_mut_ptr()) };
        Ok(())
    }

    /// Sort object members alphabetically (case-sensitive).
    /// 
    /// # Arguments
    /// * `object` - The JSON object to sort
    pub fn sort_object_case_sensitive(object: &mut CJson) -> CJsonResult<()> {
        if !object.is_object() {
            return Err(CJsonError::TypeError);
        }
        unsafe { cJSONUtils_SortObjectCaseSensitive(object.as_mut_ptr()) };
        Ok(())
    }
}

/// Re-export CJsonRef for use with pointer operations
pub use crate::cjson::CJsonRef;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cjson::CJson;

    #[test]
    fn test_json_pointer_get() {
        let json = r#"{"foo":{"bar":[1,2,3]}}"#;
        let obj = CJson::parse(json).unwrap();
        
        let result = JsonPointer::get(&obj, "/foo/bar/1").unwrap();
        assert_eq!(result.get_number_value().unwrap(), 2.0);
    }

    #[test]
    fn test_json_pointer_get_case_sensitive() {
        let json = r#"{"Foo":{"Bar":"test"}}"#;
        let obj = CJson::parse(json).unwrap();
        
        let result = JsonPointer::get_case_sensitive(&obj, "/Foo/Bar").unwrap();
        assert_eq!(result.get_string_value().unwrap(), "test");
    }

    #[test]
    fn test_json_pointer_not_found() {
        let json = r#"{"foo":"bar"}"#;
        let obj = CJson::parse(json).unwrap();
        
        assert!(JsonPointer::get(&obj, "/nonexistent").is_err());
    }

    #[test]
    fn test_json_patch_generate_and_apply() {
        let from_json = r#"{"name":"John","age":30}"#;
        let to_json = r#"{"name":"John","age":31,"city":"NYC"}"#;
        
        let mut from = CJson::parse(from_json).unwrap();
        let mut to = CJson::parse(to_json).unwrap();
        
        let patches = JsonPatch::generate(&mut from, &mut to).unwrap();
        assert!(patches.is_array());
    }

    #[test]
    fn test_json_patch_apply() {
        let obj_json = r#"{"name":"John","age":30}"#;
        let patch_json = r#"[{"op":"replace","path":"/age","value":31}]"#;
        
        let mut obj = CJson::parse(obj_json).unwrap();
        let patches = CJson::parse(patch_json).unwrap();
        
        JsonPatch::apply(&mut obj, &patches).unwrap();
        
        let age = obj.get_object_item("age").unwrap();
        assert_eq!(age.get_number_value().unwrap(), 31.0);
    }

    #[test]
    fn test_json_merge_patch_apply() {
        let target_json = r#"{"name":"John","age":30}"#;
        let patch_json = r#"{"age":31,"city":"NYC"}"#;
        
        let mut target = CJson::parse(target_json).unwrap();
        let patch = CJson::parse(patch_json).unwrap();
        
        let result = JsonMergePatch::apply(&mut target, &patch).unwrap();
        // target ownership is consumed by apply, don't use it anymore
        core::mem::forget(target); // Prevent double free
        
        let age = result.get_object_item("age").unwrap();
        assert_eq!(age.get_number_value().unwrap(), 31.0);
        
        let city = result.get_object_item("city").unwrap();
        assert_eq!(city.get_string_value().unwrap(), "NYC");
    }

    #[test]
    fn test_json_merge_patch_generate() {
        let from_json = r#"{"name":"John","age":30}"#;
        let to_json = r#"{"name":"John","age":31}"#;
        
        let mut from = CJson::parse(from_json).unwrap();
        let mut to = CJson::parse(to_json).unwrap();
        
        let patch = JsonMergePatch::generate(&mut from, &mut to).unwrap();
        assert!(patch.is_object());
    }

    #[test]
    fn test_json_utils_sort_object() {
        let json = r#"{"z":"last","a":"first","m":"middle"}"#;
        let mut obj = CJson::parse(json).unwrap();
        
        JsonUtils::sort_object(&mut obj).unwrap();
        
        // After sorting, the object should still be valid
        assert!(obj.is_object());
        assert!(obj.has_object_item("a"));
        assert!(obj.has_object_item("m"));
        assert!(obj.has_object_item("z"));
    }

    #[test]
    fn test_json_utils_sort_object_case_sensitive() {
        let json = r#"{"Z":"last","a":"first","M":"middle"}"#;
        let mut obj = CJson::parse(json).unwrap();
        
        JsonUtils::sort_object_case_sensitive(&mut obj).unwrap();
        
        assert!(obj.is_object());
        assert!(obj.has_object_item("a"));
        assert!(obj.has_object_item("M"));
        assert!(obj.has_object_item("Z"));
    }

    #[test]
    fn test_pointer_find_from_object_to() {
        let json = r#"{"foo":{"bar":"test"}}"#;
        let obj = CJson::parse(json).unwrap();
        
        // Note: This creates a new CJson from the reference for testing
        let target_owned = CJson::parse(r#"{"bar":"test"}"#).unwrap();
        
        // This might not work exactly as expected due to pointer comparison
        // but tests the API
        let _ = JsonPointer::find_from_object_to(&obj, &target_owned);
    }

    #[test]
    fn test_json_patch_add_to_array() {
        let mut patches = CJson::create_array().unwrap();
        
        let value = CJson::create_string("test").unwrap();
        JsonPatch::add_to_array(&mut patches, "add", "/foo", Some(&value)).unwrap();
        
        assert!(patches.is_array());
        assert_eq!(patches.get_array_size().unwrap(), 1);
    }

    #[test]
    fn test_complex_pointer_path() {
        let json = r#"{"users":[{"name":"Alice","age":25},{"name":"Bob","age":30}]}"#;
        let obj = CJson::parse(json).unwrap();
        
        let result = JsonPointer::get(&obj, "/users/0/name").unwrap();
        assert_eq!(result.get_string_value().unwrap(), "Alice");
        
        let result = JsonPointer::get(&obj, "/users/1/age").unwrap();
        assert_eq!(result.get_number_value().unwrap(), 30.0);
    }

    #[test]
    fn test_merge_patch_null_removal() {
        let target_json = r#"{"name":"John","age":30,"city":"NYC"}"#;
        let patch_json = r#"{"city":null}"#;
        
        let mut target = CJson::parse(target_json).unwrap();
        let patch = CJson::parse(patch_json).unwrap();
        
        let result = JsonMergePatch::apply(&mut target, &patch).unwrap();
        core::mem::forget(target); // Prevent double free
        
        // City should be removed
        assert!(result.get_object_item("city").is_err());
        assert!(result.has_object_item("name"));
        assert!(result.has_object_item("age"));
    }
}