Skip to content

Commit

Permalink
add "std-unwrap" feature to defer to std's unwrap in unwrap_throw
Browse files Browse the repository at this point in the history
  • Loading branch information
alecmocatta committed Mar 19, 2024
1 parent 78463a2 commit ab53458
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ test = false
default = ["spans", "std"]
spans = ["wasm-bindgen-macro/spans"]
std = []
std-unwrap = []
serde-serialize = ["serde", "serde_json", "std"]
enable-interning = ["std"]

Expand Down
26 changes: 20 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1327,7 +1327,7 @@ pub fn anyref_heap_live_count() -> u32 {
pub trait UnwrapThrowExt<T>: Sized {
/// Unwrap this `Option` or `Result`, but instead of panicking on failure,
/// throw an exception to JavaScript.
#[cfg_attr(debug_assertions, track_caller)]
#[cfg_attr(any(debug_assertions, feature = "std-unwrap"), track_caller)]
fn unwrap_throw(self) -> T {
if cfg!(all(debug_assertions, feature = "std")) {
let loc = core::panic::Location::caller();
Expand All @@ -1346,16 +1346,26 @@ pub trait UnwrapThrowExt<T>: Sized {
/// Unwrap this container's `T` value, or throw an error to JS with the
/// given message if the `T` value is unavailable (e.g. an `Option<T>` is
/// `None`).
#[cfg_attr(debug_assertions, track_caller)]
#[cfg_attr(any(debug_assertions, feature = "std-unwrap"), track_caller)]
fn expect_throw(self, message: &str) -> T;
}

impl<T> UnwrapThrowExt<T> for Option<T> {
#[cfg_attr(debug_assertions, track_caller)]
#[cfg(feature = "std-unwrap")]
#[track_caller]
fn unwrap_throw(self) -> T {
self.unwrap()
}

#[cfg_attr(any(debug_assertions, feature = "std-unwrap"), track_caller)]
fn expect_throw(self, message: &str) -> T {
if cfg!(all(
target_arch = "wasm32",
not(any(target_os = "emscripten", target_os = "wasi"))
not(any(
feature = "std-unwrap",
target_os = "emscripten",
target_os = "wasi"
))
)) {
match self {
Some(val) => val,
Expand All @@ -1371,11 +1381,15 @@ impl<T, E> UnwrapThrowExt<T> for Result<T, E>
where
E: core::fmt::Debug,
{
#[cfg_attr(debug_assertions, track_caller)]
#[cfg_attr(any(debug_assertions, feature = "std-unwrap"), track_caller)]
fn expect_throw(self, message: &str) -> T {
if cfg!(all(
target_arch = "wasm32",
not(any(target_os = "emscripten", target_os = "wasi"))
not(any(
feature = "std-unwrap",
target_os = "emscripten",
target_os = "wasi"
))
)) {
match self {
Ok(val) => val,
Expand Down

0 comments on commit ab53458

Please sign in to comment.