|
1 |
| -use serde_json::Value; |
| 1 | +use serde_json::{Map, Value}; |
2 | 2 | use std::ffi::{CStr, CString};
|
3 | 3 | use std::os::raw::c_char;
|
4 | 4 |
|
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 | +} |
12 | 40 |
|
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() { |
14 | 44 | Ok(str) => str,
|
15 | 45 | Err(_) => return CString::new("").unwrap().into_raw(),
|
16 | 46 | };
|
17 | 47 |
|
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 | + }; |
19 | 52 |
|
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()) |
26 | 56 | }
|
0 commit comments