Skip to content

Commit

Permalink
Added conversion from wasmi::Error to Option<Box<dyn HostError>> (byt…
Browse files Browse the repository at this point in the history
…ecodealliance#234)

This sort of conversion is useful for extracting custom error types from the
runtime when the error type is not Clone. Even when it is, it's more
efficient to unwrap it that to clone it.
  • Loading branch information
reuvenpo committed Jul 16, 2020
1 parent 1d580e3 commit 0344e55
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,11 @@ impl Trap {
pub fn kind(&self) -> &TrapKind {
&self.kind
}

/// Converts into kind of this trap.
pub fn into_kind(self) -> TrapKind {
self.kind
}
}

impl fmt::Display for Trap {
Expand Down Expand Up @@ -273,7 +278,7 @@ pub enum Error {
}

impl Error {
/// Returns [`HostError`] if this `Error` represents some host error.
/// Returns a reference to a [`HostError`] if this `Error` represents some host error.
///
/// I.e. if this error have variant [`Host`] or [`Trap`][`Trap`] with [host][`TrapKind::Host`] error.
///
Expand All @@ -282,10 +287,29 @@ impl Error {
/// [`Trap`]: enum.Error.html#variant.Trap
/// [`TrapKind::Host`]: enum.TrapKind.html#variant.Host
pub fn as_host_error(&self) -> Option<&dyn host::HostError> {
match *self {
Error::Host(ref host_err) => Some(&**host_err),
Error::Trap(ref trap) => match *trap.kind() {
TrapKind::Host(ref host_err) => Some(&**host_err),
match self {
Error::Host(host_err) => Some(&**host_err),
Error::Trap(trap) => match trap.kind() {
TrapKind::Host(host_err) => Some(&**host_err),
_ => None,
},
_ => None,
}
}

/// Returns [`HostError`] if this `Error` represents some host error.
///
/// I.e. if this error have variant [`Host`] or [`Trap`][`Trap`] with [host][`TrapKind::Host`] error.
///
/// [`HostError`]: trait.HostError.html
/// [`Host`]: enum.Error.html#variant.Host
/// [`Trap`]: enum.Error.html#variant.Trap
/// [`TrapKind::Host`]: enum.TrapKind.html#variant.Host
pub fn into_host_error(self) -> Option<Box<dyn host::HostError>> {
match self {
Error::Host(host_err) => Some(host_err),
Error::Trap(trap) => match trap.into_kind() {
TrapKind::Host(host_err) => Some(host_err),
_ => None,
},
_ => None,
Expand Down

0 comments on commit 0344e55

Please sign in to comment.