From 3a66ce2533cc46131ed965dd97f1488806367e91 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Tue, 6 Dec 2022 20:24:55 +0800 Subject: [PATCH] update: to-json ffi --- src/to-json/src/convert.rs | 7 +++---- src/to-json/src/ffi.rs | 27 ++++++++++++++++++++------- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/to-json/src/convert.rs b/src/to-json/src/convert.rs index 55f9e91..72d7dd0 100644 --- a/src/to-json/src/convert.rs +++ b/src/to-json/src/convert.rs @@ -1,11 +1,10 @@ -use serde_json as json; use crate::parser::{parser, Value}; fn json_convert(content: &str) -> Result { // convert to JSON format let data = match parser(content)? { - Value::JSON(_json) => json::to_string(&_json), - Value::YAML(_yaml) => json::to_string(&_yaml), - Value::TOML(_toml) => json::to_string(&_toml), + Value::JSON(_json) => serde_json::to_string(&_json), + Value::YAML(_yaml) => serde_json::to_string(&_yaml), + Value::TOML(_toml) => serde_json::to_string(&_toml), }; match data { Ok(data) => Ok(data), diff --git a/src/to-json/src/ffi.rs b/src/to-json/src/ffi.rs index c9569be..466bdc4 100644 --- a/src/to-json/src/ffi.rs +++ b/src/to-json/src/ffi.rs @@ -1,14 +1,27 @@ +use crate::convert::to_json; use std::ffi::{c_char, CStr, CString}; -use crate::json::to_json; + +fn to_c_string(string: String) -> *const c_char { // fetch c-style ptr of string + CString::new(string).unwrap().into_raw() +} + +unsafe fn load_c_string(ptr: *const c_char) -> String { // load string from c-style ptr + String::from( + CStr::from_ptr(ptr).to_str().unwrap() + ) +} #[no_mangle] -pub unsafe extern "C" fn free_rust_string(string: *const c_char) { - let _ = CString::from_raw(string as *mut _); +pub unsafe extern "C" fn free_rust_string(ptr: *const c_char) { + let _ = CString::from_raw(ptr as *mut _); } #[no_mangle] -pub unsafe extern "C" fn to_json_rust(content: *const c_char) -> *const c_char { - let content: &str = CStr::from_ptr(content).to_str().unwrap(); - let content: String = to_json(content); // may return empty string - CString::new(content).unwrap().into_raw() +pub unsafe extern "C" fn to_json_ffi(content: *const c_char) -> *const c_char { + let content = load_c_string(content); + let result = match to_json(&content) { // convert to JSON format + Some(data) => data, + None => String::new(), // convert failed -> empty string + }; + to_c_string(result) // return c-style ptr }