fix(ffi): return parser status and isolate thread errors
This commit is contained in:
parent
740cf9c693
commit
24438c4840
1 changed files with 234 additions and 24 deletions
130
src/lib.rs
130
src/lib.rs
|
|
@ -9,38 +9,127 @@ pub mod library;
|
|||
use crate::library::read_library;
|
||||
|
||||
use byteorder::{ByteOrder, BigEndian};
|
||||
use std::any::Any;
|
||||
use std::cell::RefCell;
|
||||
use std::mem::size_of;
|
||||
use std::ffi::{CStr, OsStr, c_char};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::ffi::{CStr, CString, c_char};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::ptr;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::str;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use arrow::ffi::{to_ffi, FFI_ArrowArray, FFI_ArrowSchema};
|
||||
use arrow::array::Array;
|
||||
use arrow::array::{Array, StructArray};
|
||||
|
||||
|
||||
thread_local! {
|
||||
static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
|
||||
fn clear_last_error() {
|
||||
LAST_ERROR.with(|last_error| *last_error.borrow_mut() = None);
|
||||
}
|
||||
|
||||
|
||||
fn set_last_error(message: String) -> i32 {
|
||||
let sanitized = message.replace('\0', "\\0");
|
||||
LAST_ERROR.with(|last_error| *last_error.borrow_mut() = Some(CString::new(sanitized).unwrap()));
|
||||
-1
|
||||
}
|
||||
|
||||
|
||||
fn describe_panic(payload: Box<dyn Any + Send>) -> String {
|
||||
if let Some(message) = payload.downcast_ref::<&str>() {
|
||||
(*message).to_string()
|
||||
} else if let Some(message) = payload.downcast_ref::<String>() {
|
||||
message.clone()
|
||||
} else {
|
||||
"unexpected panic".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn export_struct_array(
|
||||
op_name: &str,
|
||||
arr: *mut FFI_ArrowArray,
|
||||
schema: *mut FFI_ArrowSchema,
|
||||
build: impl FnOnce() -> Result<StructArray, String>,
|
||||
) -> i32 {
|
||||
clear_last_error();
|
||||
if arr.is_null() || schema.is_null() {
|
||||
return set_last_error(format!("{op_name}: Arrow output pointer was null"));
|
||||
}
|
||||
match catch_unwind(AssertUnwindSafe(build)) {
|
||||
Ok(Ok(struct_arr)) => match to_ffi(&struct_arr.to_data()) {
|
||||
Ok((ffi_arr, ffi_schema)) => {
|
||||
unsafe {
|
||||
*arr = ffi_arr;
|
||||
*schema = ffi_schema;
|
||||
}
|
||||
0
|
||||
},
|
||||
Err(err) => set_last_error(format!("{op_name}: failed to export Arrow data: {err}")),
|
||||
},
|
||||
Ok(Err(message)) => set_last_error(format!("{op_name}: {message}")),
|
||||
Err(payload) => set_last_error(format!("{op_name}: {}", describe_panic(payload))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn pathbuf_from_c(cpath: *const c_char) -> Result<PathBuf, String> {
|
||||
if cpath.is_null() {
|
||||
return Err("path pointer was null".to_string());
|
||||
}
|
||||
|
||||
let cstr = unsafe { CStr::from_ptr(cpath) };
|
||||
#[cfg(unix)]
|
||||
{
|
||||
return Ok(PathBuf::from(std::ffi::OsString::from_vec(cstr.to_bytes().to_vec())));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let ustr = str::from_utf8(cstr.to_bytes())
|
||||
.map_err(|_| "Non-UTF8 paths are not supported".to_string())?;
|
||||
return Ok(PathBuf::from(ustr));
|
||||
}
|
||||
#[allow(unreachable_code)]
|
||||
Err("Unsupported OS".to_string())
|
||||
}
|
||||
|
||||
|
||||
/// Return this thread's last parser error, or null if its last call succeeded.
|
||||
/// The returned string remains valid until this thread's next parser call or exit.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn last_error_message() -> *const c_char {
|
||||
LAST_ERROR.with(|last_error| last_error.borrow()
|
||||
.as_ref()
|
||||
.map_or(ptr::null(), |message| message.as_ptr()))
|
||||
}
|
||||
|
||||
|
||||
/// Read a GDSII file and export its Arrow data. Return 0 on success or -1 on error.
|
||||
///
|
||||
/// # Safety
|
||||
/// `cpath` must point to a null-terminated path. Non-null output pointers must
|
||||
/// point to initialized, writable Arrow FFI structures. Null pointers are rejected.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn read_path(
|
||||
cpath: *const c_char,
|
||||
arr: *mut FFI_ArrowArray,
|
||||
schema: *mut FFI_ArrowSchema,
|
||||
) {
|
||||
let cstr = unsafe { CStr::from_ptr(cpath) };
|
||||
let path: &Path;
|
||||
if cfg!(unix) {
|
||||
let osstr = OsStr::from_bytes(cstr.to_bytes());
|
||||
path = osstr.as_ref();
|
||||
} else if cfg!(windows) {
|
||||
let ustr = str::from_utf8(cstr.to_bytes()).expect("Non-UTF8 paths are not supported");
|
||||
path = ustr.as_ref();
|
||||
} else {
|
||||
panic!("Unsupported OS");
|
||||
}
|
||||
|
||||
let input = fs::read(path).expect("File read failed");
|
||||
let (_input, struct_arr) = read_library(&input).expect("Read failed");
|
||||
unsafe { (*arr, *schema) = to_ffi(&struct_arr.to_data()).unwrap(); }
|
||||
) -> i32 {
|
||||
export_struct_array("read_path", arr, schema, || {
|
||||
let path = pathbuf_from_c(cpath)?;
|
||||
let input = fs::read(Path::new(&path))
|
||||
.map_err(|err| format!("file read failed for {}: {err}", path.display()))?;
|
||||
let (_input, struct_arr) = read_library(&input)
|
||||
.map_err(|err| format!("read failed: {err:?}"))?;
|
||||
Ok(struct_arr)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -116,4 +205,3 @@ pub unsafe extern "C" fn u16_to_i16(arr: *mut u16, size: usize) -> u16 { impl_i1
|
|||
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn i16_to_i16(arr: *mut i16, size: usize) -> i16 { impl_i16be!(i16, arr, size) }
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue