From 0d075831a8d215651d85e4eeb7c5ccf02e17b854 Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Mon, 9 Aug 2021 16:20:19 +0200 Subject: [PATCH] Remmove panic by adding `Default` bound --- Cargo.toml | 3 ++- src/convert/slices.rs | 15 ++++++++------- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 828dd99b466..df0fe064e11 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] @@ -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' } diff --git a/src/convert/slices.rs b/src/convert/slices.rs index 5286685882e..a0c08602755 100644 --- a/src/convert/slices.rs +++ b/src/convert/slices.rs @@ -146,7 +146,7 @@ cfg_if! { } if_std! { - use std::convert::TryFrom; + use std::{hint, iter}; impl IntoWasmAbi for Vec where Box<[T]>: IntoWasmAbi { type Abi = as IntoWasmAbi>::Abi; @@ -190,20 +190,21 @@ if_std! { fn none() -> WasmSlice { null_slice() } } - impl FromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi { + impl FromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi { type Abi = as FromWasmAbi>::Abi; #[inline] unsafe fn from_abi(js: Self::Abi) -> Self { - let result = <[T; N]>::try_from(>::from(>::from_abi(js))); - return match result { - Ok(arr) => arr, - Err(_) => panic!("JS array length does not match Rust array") + let vec = >::from(>::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 OptionFromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi { + impl OptionFromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi { #[inline] fn is_none(abi: &WasmSlice) -> bool { abi.ptr == 0 } }