Skip to content

Commit

Permalink
Remmove panic by adding Default bound
Browse files Browse the repository at this point in the history
  • Loading branch information
Jules-Bertholet committed Aug 9, 2021
1 parent f3f7506 commit 0d07583
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ test = false
[features]
default = ["spans", "std"]
spans = ["wasm-bindgen-macro/spans"]
std = []
std = ["array-init"]
serde-serialize = ["serde", "serde_json", "std"]
nightly = []
enable-interning = ["std"]
Expand All @@ -40,6 +40,7 @@ wasm-bindgen-macro = { path = "crates/macro", version = "=0.2.75" }
serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }
cfg-if = "1.0.0"
array-init = { version = "2.0.0", optional = true }

[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
js-sys = { path = 'crates/js-sys', version = '0.3.52' }
Expand Down
15 changes: 8 additions & 7 deletions src/convert/slices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ cfg_if! {
}

if_std! {
use std::convert::TryFrom;
use std::{hint, iter};

impl<T> IntoWasmAbi for Vec<T> where Box<[T]>: IntoWasmAbi<Abi = WasmSlice> {
type Abi = <Box<[T]> as IntoWasmAbi>::Abi;
Expand Down Expand Up @@ -190,20 +190,21 @@ if_std! {
fn none() -> WasmSlice { null_slice() }
}

impl<T, const N: usize> FromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi<Abi = WasmSlice> {
impl<T: Default, const N: usize> FromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi<Abi = WasmSlice> {
type Abi = <Box<[T]> as FromWasmAbi>::Abi;

#[inline]
unsafe fn from_abi(js: Self::Abi) -> Self {
let result = <[T; N]>::try_from(<Vec<T>>::from(<Box<[T]>>::from_abi(js)));
return match result {
Ok(arr) => arr,
Err(_) => panic!("JS array length does not match Rust array")
let vec = <Vec<T>>::from(<Box<[T]>>::from_abi(js));
let iter = vec.into_iter().chain(iter::repeat_with(T::default));
match array_init::from_iter(iter) {
Some(arr) => arr,
None => hint::unreachable_unchecked(),
}
}
}

impl<T, const N: usize> OptionFromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi<Abi = WasmSlice> {
impl<T: Default, const N: usize> OptionFromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi<Abi = WasmSlice> {
#[inline]
fn is_none(abi: &WasmSlice) -> bool { abi.ptr == 0 }
}
Expand Down

0 comments on commit 0d07583

Please sign in to comment.