fxkit 0.1.2

Useful utilities for writting Rust CLI tools
Documentation
use std::ffi::{CStr, CString, c_char};

/// Converts a Rust `&str` to a null-terminated C string (`*const c_char`).
///
/// # Safety
///
/// The returned pointer is allocated on the heap and the caller **must eventually
/// reclaim it** using `CString::from_raw()`. Failing to do so will leak memory.
///
/// The caller must **not use the pointer after reclaiming** it.
pub unsafe fn str_to_cstr(text: &str) -> *const c_char {
    if text.is_empty() {
        return c"".as_ptr();
    }

    let text_cstr = CString::new(text).unwrap_or_default();

    text_cstr.into_raw() as *const c_char
}

/// Converts a null-terminated C string (`*const c_char`) into a Rust `String`.
///
/// # Safety
///
/// - The `text` pointer **must be valid** and point to a null-terminated string.
/// - Passing a dangling or non-null-terminated pointer **may cause undefined behavior**.
/// - Passing `NULL` is safe; it returns an empty string.
pub unsafe fn cstr_to_str(text: *const c_char) -> String {
    if text.is_null() {
        return String::from("NULL");
    }

    let text = unsafe { CStr::from_ptr(text).to_string_lossy() };

    text.to_string()
}