From 576d940fe1fb22120fa1fc9bae7daa4400fa1fa2 Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Tue, 13 Jul 2021 20:18:01 +0200 Subject: [PATCH 1/2] Implement To/FromWasmAbi for arrays --- src/convert/slices.rs | 34 ++++++++++++++++++++++++++++++++++ src/describe.rs | 6 ++++++ 2 files changed, 40 insertions(+) diff --git a/src/convert/slices.rs b/src/convert/slices.rs index 9d0970f4e6a..5286685882e 100644 --- a/src/convert/slices.rs +++ b/src/convert/slices.rs @@ -146,6 +146,8 @@ cfg_if! { } if_std! { + use std::convert::TryFrom; + impl IntoWasmAbi for Vec where Box<[T]>: IntoWasmAbi { type Abi = as IntoWasmAbi>::Abi; @@ -174,6 +176,38 @@ if_std! { fn is_none(abi: &WasmSlice) -> bool { abi.ptr == 0 } } + impl IntoWasmAbi for [T; N] where Box<[T]>: IntoWasmAbi { + type Abi = as IntoWasmAbi>::Abi; + + #[inline] + fn into_abi(self) -> Self::Abi { + >::from(self).into_abi() + } + } + + impl OptionIntoWasmAbi for [T; N] where Box<[T]>: IntoWasmAbi { + #[inline] + fn none() -> WasmSlice { null_slice() } + } + + 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") + } + } + } + + impl OptionFromWasmAbi for [T; N] where Box<[T]>: FromWasmAbi { + #[inline] + fn is_none(abi: &WasmSlice) -> bool { abi.ptr == 0 } + } + impl IntoWasmAbi for String { type Abi = as IntoWasmAbi>::Abi; diff --git a/src/describe.rs b/src/describe.rs index 2d424f8f3f7..29c4a475f16 100644 --- a/src/describe.rs +++ b/src/describe.rs @@ -155,6 +155,12 @@ if_std! { >::describe(); } } + + impl WasmDescribe for [T; N] where Box<[T]>: WasmDescribe { + fn describe() { + >::describe(); + } + } } impl WasmDescribe for Option { From 90c4c0c5487e58fda72ab68c939836613c884e57 Mon Sep 17 00:00:00 2001 From: Jules Bertholet Date: Wed, 14 Jul 2021 19:00:28 +0200 Subject: [PATCH 2/2] Document #2614 --- guide/src/reference/types/boxed-jsvalue-slice.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/guide/src/reference/types/boxed-jsvalue-slice.md b/guide/src/reference/types/boxed-jsvalue-slice.md index c349ad15abc..8060d194a7c 100644 --- a/guide/src/reference/types/boxed-jsvalue-slice.md +++ b/guide/src/reference/types/boxed-jsvalue-slice.md @@ -4,6 +4,8 @@ |:---:|:---:|:---:|:---:|:---:|:---:|:---:| | Yes | No | No | Yes | Yes | Yes | A JavaScript `Array` object | +Boxed slices of imported JS types and exported Rust types are also supported. `Vec` is supported wherever `Box<[T]>` is. + ## Example Rust Usage ```rust