Skip to content

Commit

Permalink
rust: add errorcontainer abstraction
Browse files Browse the repository at this point in the history
  • Loading branch information
axic committed Mar 24, 2021
1 parent 3ed702c commit 21ef74d
Showing 1 changed file with 47 additions and 12 deletions.
59 changes: 47 additions & 12 deletions bindings/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,58 @@ mod sys;
use std::ffi::CString;
use std::ptr::NonNull;

/// A safe container for handling the low-level FizzyError struct.
struct CErrorContainer(Box<sys::FizzyError>);

impl CErrorContainer {
/// Create a safe, boxed, and zero initalised container.
fn new() -> Self {
CErrorContainer {
0: Box::new(sys::FizzyError {
code: 0,
message: [0i8; 256],
}),
}
}

/// Return a pointer passable to low-level functions (validate, parse, instantiate).
///
/// # Safety
/// The returned pointer is still onwed by this struct, and thus not valid after this struct goes out of scope.
unsafe fn as_mut_ptr(&mut self) -> *mut sys::FizzyError {
&mut *self.0
}

/// Return the underlying error code.
fn code(&self) -> u32 {
self.0.code
}

/// Return an owned String copy of the underlying message.
fn message(&self) -> String {
unsafe {
std::ffi::CStr::from_ptr(self.0.message.as_ptr())
.to_string_lossy()
.into_owned()
}
}
}

/// Parse and validate the input according to WebAssembly 1.0 rules. Returns true if the supplied input is valid.
pub fn validate<T: AsRef<[u8]>>(input: T) -> Result<(), String> {
let mut err = Box::new(sys::FizzyError {
code: 0,
message: [0i8; 256],
});
let ret =
unsafe { sys::fizzy_validate(input.as_ref().as_ptr(), input.as_ref().len(), &mut *err) };
let mut err = CErrorContainer::new();
let ret = unsafe {
sys::fizzy_validate(
input.as_ref().as_ptr(),
input.as_ref().len(),
err.as_mut_ptr(),
)
};
if ret {
Ok(())
} else {
let msg = unsafe {
std::ffi::CStr::from_ptr(err.message.as_ptr())
.to_string_lossy()
.into_owned()
};
println!("error: {}", msg);
let msg = err.message();
println!("error: {} [{}]", err.code(), msg);
Err(msg)
}
}
Expand Down

0 comments on commit 21ef74d

Please sign in to comment.