use std::{
error::Error,
ffi::{CStr, CString, c_void},
mem::forget,
};
#[repr(C)]
pub struct C3String {
ptr: *const c_void,
len: usize,
}
impl C3String {
fn get_ptr<P>(value: P) -> (*const i8, usize)
where
P: Into<String>,
{
let value = value.into() as String;
let cstring = CString::new(value.clone()).expect("Unable to convert String to CString");
let ptr = cstring.as_ptr();
let len = value.len();
forget(cstring);
(ptr, len)
}
fn str_from_ptr(ptr: *mut i8) -> Result<&'static str, Box<dyn Error>> {
let cstring = unsafe { CStr::from_ptr(ptr) };
let string = cstring.to_str()?;
Ok(string)
}
pub fn ptr(&self) -> *const c_void {
self.ptr
}
pub fn len(&self) -> usize {
self.len
}
pub fn into_c3_string<P>(value: P) -> Self
where
P: Into<String>,
{
let (ptr, len) = Self::get_ptr(value);
Self {
ptr: ptr as *const c_void,
len: len,
}
}
pub fn str_from_c3_string(&self) -> Result<&'static str, Box<dyn Error>> {
Self::str_from_ptr(self.ptr.cast_mut() as *mut i8)
}
pub fn into_c3_zstring<P>(value: P) -> C3ZString
where
P: Into<String>,
{
Self::get_ptr(value).0 as *const u8
}
pub fn str_from_c3_zstring(ptr: C3ZString) -> Result<&'static str, Box<dyn Error>> {
Self::str_from_ptr(ptr.cast_mut() as *mut i8)
}
pub fn into_c3_wstring<P>(value: P) -> C3WString
where
P: Into<String>,
{
Self::get_ptr(value).0 as *const u16
}
pub fn str_from_c3_wstring(ptr: C3WString) -> Result<&'static str, Box<dyn Error>> {
Self::str_from_ptr(ptr.cast_mut() as *mut i8)
}
pub fn into_c3_dstring<P>(value: P) -> C3DString
where
P: Into<String>,
{
Self::get_ptr(value).0 as *const c_void
}
pub fn str_from_c3_dstring(ptr: C3DString) -> Result<&'static str, Box<dyn Error>> {
Self::str_from_ptr(ptr.cast_mut() as *mut i8)
}
}
pub type C3ZString = *const u8;
pub type C3WString = *const u16;
pub type C3DString = *const c_void;