rust_to_dtr/
lib.rs

1// syn docs: https://docs.rs/syn/2.0.60/syn/index.html
2extern crate syn;
3
4pub mod common;
5pub mod errors;
6pub mod instruction;
7pub mod optimize;
8pub mod rust_to_dtr_c;
9pub mod translate;
10
11use std::ffi::{CStr, CString};
12
13use std::os::raw::c_char;
14use std::ptr;
15
16use instruction::Instruction;
17
18pub fn version() -> &'static str {
19    env!("CARGO_PKG_VERSION")
20}
21
22pub fn parse_to_dtr(rust_code: &str) -> Result<String, errors::NotTranslatableError> {
23    rust_to_dtr_c::parse_to_dtr(rust_code)
24}
25
26#[no_mangle]
27pub extern "C" fn rust_string_to_dtr_string(rust_code: *const c_char) -> *const c_char {
28    if rust_code.is_null() {
29        return ptr::null();
30    }
31
32    // Convert the C string to a Rust &str
33    let c_str = unsafe { CStr::from_ptr(rust_code) };
34    let rust_str = match c_str.to_str() {
35        Ok(s) => s,
36        Err(_) => return ptr::null(),
37    };
38
39    // Call the function to convert the Rust string to DTR string
40    let dtr_string = rust_to_dtr_c::parse_to_dtr(rust_str).unwrap_or_default();
41
42    // Convert the DTR string to CString and return the raw pointer
43    let c_string = match CString::new(dtr_string) {
44        Ok(s) => s,
45        Err(_) => return ptr::null(),
46    };
47
48    c_string.into_raw()
49}
50
51#[no_mangle]
52pub extern "C" fn free_cstring(s: *mut c_char) {
53    if s.is_null() {
54        return;
55    }
56    unsafe {
57        let _ = CString::from_raw(s);
58    }
59}
60
61mod tests;