use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::ptr;
pub unsafe fn c_str_to_rust<'a>(ptr: *const c_char) -> Option<&'a str> {
if ptr.is_null() {
return None;
}
CStr::from_ptr(ptr).to_str().ok()
}
pub fn rust_str_to_c(s: &str) -> *mut c_char {
match CString::new(s) {
Ok(c_str) => c_str.into_raw(),
Err(_) => ptr::null_mut(),
}
}
pub fn option_to_ptr<T>(opt: Option<T>) -> *mut T {
match opt {
Some(val) => Box::into_raw(Box::new(val)),
None => ptr::null_mut(),
}
}
pub unsafe fn ptr_to_option<'a, T>(ptr: *const T) -> Option<&'a T> {
if ptr.is_null() {
None
} else {
Some(&*ptr)
}
}
pub unsafe fn ptr_to_option_mut<'a, T>(ptr: *mut T) -> Option<&'a mut T> {
if ptr.is_null() {
None
} else {
Some(&mut *ptr)
}
}
use super::types::{
AnalyzerInternal, BuilderInternal, CAnalyzer, CAnalyzerBuilder, CReport, CReportInternal,
};
pub unsafe fn cast_analyzer(ptr: *const CAnalyzer) -> Option<&'static AnalyzerInternal> {
if ptr.is_null() {
None
} else {
Some(&*(ptr as *const AnalyzerInternal))
}
}
pub unsafe fn cast_analyzer_mut(ptr: *mut CAnalyzer) -> Option<&'static mut AnalyzerInternal> {
if ptr.is_null() {
None
} else {
Some(&mut *(ptr as *mut AnalyzerInternal))
}
}
pub unsafe fn cast_report(ptr: *const CReport) -> Option<&'static CReportInternal> {
if ptr.is_null() {
None
} else {
Some(&*(ptr as *const CReportInternal))
}
}
pub unsafe fn cast_builder(ptr: *const CAnalyzerBuilder) -> Option<&'static BuilderInternal> {
if ptr.is_null() {
None
} else {
Some(&*(ptr as *const BuilderInternal))
}
}
pub unsafe fn cast_builder_mut(ptr: *mut CAnalyzerBuilder) -> Option<&'static mut BuilderInternal> {
if ptr.is_null() {
None
} else {
Some(&mut *(ptr as *mut BuilderInternal))
}
}
#[macro_export]
macro_rules! null_check {
($ptr:expr) => {
if $ptr.is_null() {
$crate::ffi::errors::set_last_error("Null pointer provided".to_string());
return $crate::ffi::types::CErrorCode::InvalidPointer;
}
};
($ptr:expr, $ret:expr) => {
if $ptr.is_null() {
$crate::ffi::errors::set_last_error("Null pointer provided".to_string());
return $ret;
}
};
}
#[macro_export]
macro_rules! null_check_opt {
($ptr:expr) => {
if $ptr.is_null() {
$crate::ffi::errors::set_last_error("Null pointer provided".to_string());
return None;
}
};
}