Fix from_cstring from taking ownership

This commit is contained in:
Sofia 2025-06-29 18:19:59 +03:00
parent 814b816450
commit 7b93ab5d2e
2 changed files with 7 additions and 6 deletions

View File

@ -142,12 +142,13 @@ impl<'ctx> Module<'ctx> {
triple,
c"generic".as_ptr(),
c"".as_ptr(),
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelDefault,
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
);
let data_layout = LLVMCreateTargetDataLayout(target_machine);
LLVMSetTarget(self.module_ref, triple);
LLVMSetModuleDataLayout(self.module_ref, data_layout);
let mut err = ErrorMessageHolder::null();
@ -178,7 +179,7 @@ impl<'ctx> Module<'ctx> {
);
err.into_result().unwrap();
Ok(from_cstring(LLVMPrintModuleToString(self.module_ref)).expect("UTF8-err"))
from_cstring(LLVMPrintModuleToString(self.module_ref)).ok_or("UTF-8 error".to_owned())
}
}
}

View File

@ -1,5 +1,5 @@
use std::{
ffi::{CString, c_char},
ffi::{CStr, CString, c_char},
ptr::null_mut,
};
@ -10,11 +10,11 @@ pub fn into_cstring<T: Into<String>>(value: T) -> CString {
unsafe { CString::from_vec_with_nul_unchecked((string + "\0").into_bytes()) }
}
pub fn from_cstring(value: *mut c_char) -> Option<String> {
if value.is_null() {
pub fn from_cstring(pointer: *mut c_char) -> Option<String> {
if pointer.is_null() {
None
} else {
unsafe { CString::from_raw(value).into_string().ok() }
unsafe { CStr::from_ptr(pointer).to_str().ok().map(|s| s.to_owned()) }
}
}