Browse Source

update: to-json ffi

dev
Dnomd343 2 years ago
parent
commit
3a66ce2533
  1. 7
      src/to-json/src/convert.rs
  2. 27
      src/to-json/src/ffi.rs

7
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<String, String> { // 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),

27
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
}

Loading…
Cancel
Save