Skip to content

Commit 8cca1f9

Browse files
committed
changes :
- Added Error handling - memory management improved
1 parent b46fb6c commit 8cca1f9

File tree

1 file changed

+46
-16
lines changed

1 file changed

+46
-16
lines changed

src/lib.rs

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,56 @@
1-
use serde_json::Value;
1+
use serde_json::{Map, Value};
22
use std::ffi::{CStr, CString};
33
use std::os::raw::c_char;
44

5-
#[no_mangle]
6-
pub extern "C" fn parse_json(input: *const c_char) -> *mut c_char {
7-
let c_str = unsafe {
8-
assert!(!input.is_null());
9-
10-
CStr::from_ptr(input)
11-
};
5+
fn parse_value(value: &Value) -> String {
6+
match value {
7+
Value::Null => "null".to_string(),
8+
Value::Bool(val) => val.to_string(),
9+
Value::Number(val) => val.to_string(),
10+
Value::String(val) => format!("\"{}\"", val),
11+
Value::Array(val) => {
12+
let mut result = String::new();
13+
result.push('[');
14+
for item in val {
15+
result += &parse_value(item);
16+
result.push(',');
17+
}
18+
if !val.is_empty() {
19+
result.pop();
20+
}
21+
result.push(']');
22+
result
23+
}
24+
Value::Object(val) => {
25+
let mut result = String::new();
26+
result.push('{');
27+
for (key, value) in val {
28+
result.push_str(&format!("\"{}\":", key));
29+
result += &parse_value(value);
30+
result.push(',');
31+
}
32+
if !val.is_empty() {
33+
result.pop();
34+
}
35+
result.push('}');
36+
result
37+
}
38+
}
39+
}
1240

13-
let input_str = match c_str.to_str() {
41+
#[no_mangle]
42+
pub unsafe extern "C" fn parse_json(input: *const c_char) -> *mut c_char {
43+
let input_str = match CStr::from_ptr(input).to_str() {
1444
Ok(str) => str,
1545
Err(_) => return CString::new("").unwrap().into_raw(),
1646
};
1747

18-
let result = serde_json::from_str::<Value>(input_str);
48+
let result = match serde_json::from_str::<Value>(input_str) {
49+
Ok(data) => parse_value(&data),
50+
Err(err) => format!("Failed to parse JSON: {}", err),
51+
};
1952

20-
match result {
21-
Ok(data) => CString::new(format!("{:?}", data)).unwrap().into_raw(),
22-
Err(err) => CString::new(format!("Failed to parse JSON: {}", err))
23-
.unwrap()
24-
.into_raw(),
25-
}
53+
CString::new(result)
54+
.map(|s| s.into_raw())
55+
.unwrap_or_else(|_| CString::new("").unwrap().into_raw())
2656
}

0 commit comments

Comments
 (0)