Skip to content

Commit 9b37613

Browse files
authored
Improve the performance of 'string enums' (#3915)
1 parent fa6d2bc commit 9b37613

File tree

16 files changed

+298
-74
lines changed

16 files changed

+298
-74
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
* Generate JS bindings for WebIDL dictionary setters instead of using `Reflect`. This increases the size of the Web API bindings but should be more performant. Also, importing getters/setters from JS now supports specifying the JS attribute name as a string, e.g. `#[wasm_bindgen(method, setter = "x-cdm-codecs")]`.
3232
[#3898](https://github.com/rustwasm/wasm-bindgen/pull/3898)
3333

34+
* Greatly improve the performance of sending WebIDL 'string enums' across the JavaScript boundary by converting the enum variant string to/from an int.
35+
[#3915](https://github.com/rustwasm/wasm-bindgen/pull/3915)
36+
3437
### Fixed
3538

3639
* Copy port from headless test server when using `WASM_BINDGEN_TEST_ADDRESS`.

benchmarks/index.html

+2-2
Original file line numberDiff line numberDiff line change
@@ -277,12 +277,12 @@ <h1>wasm-bindgen benchmarks</h1>
277277

278278
<tr>
279279
<td>
280-
Call a custom JS function with an enum value parameter
280+
Call a custom JS function with a string enum value parameter
281281

282282
<a class='about-open' href='#'>(?)</a>
283283

284284
<p class='about'>
285-
Benchmarks the speed of passing enum values to javascript
285+
Benchmarks the speed of passing string enums to javascript
286286
</p>
287287
</td>
288288

crates/backend/src/ast.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ pub enum ImportKind {
163163
/// Importing a type/class
164164
Type(ImportType),
165165
/// Importing a JS enum
166-
Enum(ImportEnum),
166+
Enum(StringEnum),
167167
}
168168

169169
/// A function being imported from JS
@@ -302,10 +302,10 @@ pub struct ImportType {
302302
pub wasm_bindgen: Path,
303303
}
304304

305-
/// The metadata for an Enum being imported
305+
/// The metadata for a String Enum
306306
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
307307
#[derive(Clone)]
308-
pub struct ImportEnum {
308+
pub struct StringEnum {
309309
/// The Rust enum's visibility
310310
pub vis: syn::Visibility,
311311
/// The Rust enum's identifiers
@@ -404,7 +404,7 @@ pub struct StructField {
404404
pub wasm_bindgen: Path,
405405
}
406406

407-
/// Information about an Enum being exported
407+
/// The metadata for an Enum
408408
#[cfg_attr(feature = "extra-traits", derive(Debug, PartialEq, Eq))]
409409
#[derive(Clone)]
410410
pub struct Enum {

crates/backend/src/codegen.rs

+71-52
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::encode;
33
use crate::encode::EncodeChunk;
44
use crate::Diagnostic;
55
use once_cell::sync::Lazy;
6-
use proc_macro2::{Ident, Literal, Span, TokenStream};
6+
use proc_macro2::{Ident, Span, TokenStream};
77
use quote::format_ident;
88
use quote::quote_spanned;
99
use quote::{quote, ToTokens};
@@ -1075,117 +1075,136 @@ impl ToTokens for ast::ImportType {
10751075
}
10761076
}
10771077

1078-
impl ToTokens for ast::ImportEnum {
1078+
impl ToTokens for ast::StringEnum {
10791079
fn to_tokens(&self, tokens: &mut TokenStream) {
10801080
let vis = &self.vis;
1081-
let name = &self.name;
1082-
let expect_string = format!("attempted to convert invalid {} into JSValue", name);
1081+
let enum_name = &self.name;
1082+
let name_str = enum_name.to_string();
1083+
let name_len = name_str.len() as u32;
1084+
let name_chars = name_str.chars().map(u32::from);
10831085
let variants = &self.variants;
1084-
let variant_strings = &self.variant_values;
1086+
let variant_count = self.variant_values.len() as u32;
1087+
let variant_values = &self.variant_values;
1088+
let variant_indices = (0..variant_count).collect::<Vec<_>>();
1089+
let invalid = variant_count;
1090+
let hole = variant_count + 1;
10851091
let attrs = &self.rust_attrs;
10861092

1087-
let mut current_idx: usize = 0;
1088-
let variant_indexes: Vec<Literal> = variants
1089-
.iter()
1090-
.map(|_| {
1091-
let this_index = current_idx;
1092-
current_idx += 1;
1093-
Literal::usize_unsuffixed(this_index)
1094-
})
1095-
.collect();
1096-
1097-
// Borrow variant_indexes because we need to use it multiple times inside the quote! macro
1098-
let variant_indexes_ref = &variant_indexes;
1093+
let invalid_to_str_msg = format!(
1094+
"Converting an invalid string enum ({}) back to a string is currently not supported",
1095+
enum_name
1096+
);
10991097

11001098
// A vector of EnumName::VariantName tokens for this enum
11011099
let variant_paths: Vec<TokenStream> = self
11021100
.variants
11031101
.iter()
1104-
.map(|v| quote!(#name::#v).into_token_stream())
1102+
.map(|v| quote!(#enum_name::#v).into_token_stream())
11051103
.collect();
11061104

11071105
// Borrow variant_paths because we need to use it multiple times inside the quote! macro
11081106
let variant_paths_ref = &variant_paths;
11091107

11101108
let wasm_bindgen = &self.wasm_bindgen;
11111109

1110+
let describe_variants = self.variant_values.iter().map(|variant_value| {
1111+
let length = variant_value.len() as u32;
1112+
let chars = variant_value.chars().map(u32::from);
1113+
quote! {
1114+
inform(#length);
1115+
#(inform(#chars);)*
1116+
}
1117+
});
1118+
11121119
(quote! {
11131120
#(#attrs)*
1114-
#vis enum #name {
1115-
#(#variants = #variant_indexes_ref,)*
1121+
#[non_exhaustive]
1122+
#[repr(u32)]
1123+
#vis enum #enum_name {
1124+
#(#variants = #variant_indices,)*
11161125
#[automatically_derived]
11171126
#[doc(hidden)]
1118-
__Nonexhaustive,
1127+
__Invalid
11191128
}
11201129

11211130
#[automatically_derived]
1122-
impl #name {
1123-
fn from_str(s: &str) -> Option<#name> {
1131+
impl #enum_name {
1132+
fn from_str(s: &str) -> Option<#enum_name> {
11241133
match s {
1125-
#(#variant_strings => Some(#variant_paths_ref),)*
1134+
#(#variant_values => Some(#variant_paths_ref),)*
11261135
_ => None,
11271136
}
11281137
}
11291138

11301139
fn to_str(&self) -> &'static str {
11311140
match self {
1132-
#(#variant_paths_ref => #variant_strings,)*
1133-
#name::__Nonexhaustive => panic!(#expect_string),
1141+
#(#variant_paths_ref => #variant_values,)*
1142+
#enum_name::__Invalid => panic!(#invalid_to_str_msg),
11341143
}
11351144
}
11361145

1137-
#vis fn from_js_value(obj: &#wasm_bindgen::JsValue) -> Option<#name> {
1146+
#vis fn from_js_value(obj: &#wasm_bindgen::JsValue) -> Option<#enum_name> {
11381147
obj.as_string().and_then(|obj_str| Self::from_str(obj_str.as_str()))
11391148
}
11401149
}
11411150

1142-
// It should really be using &str for all of these, but that requires some major changes to cli-support
11431151
#[automatically_derived]
1144-
impl #wasm_bindgen::describe::WasmDescribe for #name {
1145-
fn describe() {
1146-
<#wasm_bindgen::JsValue as #wasm_bindgen::describe::WasmDescribe>::describe()
1147-
}
1148-
}
1149-
1150-
#[automatically_derived]
1151-
impl #wasm_bindgen::convert::IntoWasmAbi for #name {
1152-
type Abi = <#wasm_bindgen::JsValue as #wasm_bindgen::convert::IntoWasmAbi>::Abi;
1152+
impl #wasm_bindgen::convert::IntoWasmAbi for #enum_name {
1153+
type Abi = u32;
11531154

11541155
#[inline]
1155-
fn into_abi(self) -> Self::Abi {
1156-
<#wasm_bindgen::JsValue as #wasm_bindgen::convert::IntoWasmAbi>::into_abi(self.into())
1156+
fn into_abi(self) -> u32 {
1157+
self as u32
11571158
}
11581159
}
11591160

11601161
#[automatically_derived]
1161-
impl #wasm_bindgen::convert::FromWasmAbi for #name {
1162-
type Abi = <#wasm_bindgen::JsValue as #wasm_bindgen::convert::FromWasmAbi>::Abi;
1162+
impl #wasm_bindgen::convert::FromWasmAbi for #enum_name {
1163+
type Abi = u32;
11631164

1164-
unsafe fn from_abi(js: Self::Abi) -> Self {
1165-
let s = <#wasm_bindgen::JsValue as #wasm_bindgen::convert::FromWasmAbi>::from_abi(js);
1166-
#name::from_js_value(&s).unwrap_or(#name::__Nonexhaustive)
1165+
unsafe fn from_abi(val: u32) -> Self {
1166+
match val {
1167+
#(#variant_indices => #variant_paths_ref,)*
1168+
#invalid => #enum_name::__Invalid,
1169+
_ => unreachable!("The JS binding should only ever produce a valid value or the specific 'invalid' value"),
1170+
}
11671171
}
11681172
}
11691173

11701174
#[automatically_derived]
1171-
impl #wasm_bindgen::convert::OptionIntoWasmAbi for #name {
1175+
impl #wasm_bindgen::convert::OptionFromWasmAbi for #enum_name {
11721176
#[inline]
1173-
fn none() -> Self::Abi { <::js_sys::Object as #wasm_bindgen::convert::OptionIntoWasmAbi>::none() }
1177+
fn is_none(val: &u32) -> bool { *val == #hole }
11741178
}
11751179

11761180
#[automatically_derived]
1177-
impl #wasm_bindgen::convert::OptionFromWasmAbi for #name {
1181+
impl #wasm_bindgen::convert::OptionIntoWasmAbi for #enum_name {
11781182
#[inline]
1179-
fn is_none(abi: &Self::Abi) -> bool { <::js_sys::Object as #wasm_bindgen::convert::OptionFromWasmAbi>::is_none(abi) }
1183+
fn none() -> Self::Abi { #hole }
1184+
}
1185+
1186+
#[automatically_derived]
1187+
impl #wasm_bindgen::describe::WasmDescribe for #enum_name {
1188+
fn describe() {
1189+
use #wasm_bindgen::describe::*;
1190+
inform(STRING_ENUM);
1191+
inform(#name_len);
1192+
#(inform(#name_chars);)*
1193+
inform(#variant_count);
1194+
#(#describe_variants)*
1195+
}
11801196
}
11811197

11821198
#[automatically_derived]
1183-
impl From<#name> for #wasm_bindgen::JsValue {
1184-
fn from(obj: #name) -> #wasm_bindgen::JsValue {
1185-
#wasm_bindgen::JsValue::from(obj.to_str())
1199+
impl #wasm_bindgen::__rt::core::convert::From<#enum_name> for
1200+
#wasm_bindgen::JsValue
1201+
{
1202+
fn from(val: #enum_name) -> Self {
1203+
#wasm_bindgen::JsValue::from_str(val.to_str())
11861204
}
11871205
}
1188-
}).to_tokens(tokens);
1206+
})
1207+
.to_tokens(tokens);
11891208
}
11901209
}
11911210

crates/backend/src/encode.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -339,8 +339,8 @@ fn shared_import_type<'a>(i: &'a ast::ImportType, intern: &'a Interner) -> Impor
339339
}
340340
}
341341

342-
fn shared_import_enum<'a>(_i: &'a ast::ImportEnum, _intern: &'a Interner) -> ImportEnum {
343-
ImportEnum {}
342+
fn shared_import_enum<'a>(_i: &'a ast::StringEnum, _intern: &'a Interner) -> StringEnum {
343+
StringEnum {}
344344
}
345345

346346
fn shared_struct<'a>(s: &'a ast::Struct, intern: &'a Interner) -> Struct<'a> {

crates/cli-support/src/descriptor.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ tys! {
3434
EXTERNREF
3535
NAMED_EXTERNREF
3636
ENUM
37+
STRING_ENUM
3738
RUST_STRUCT
3839
CHAR
3940
OPTIONAL
@@ -67,7 +68,16 @@ pub enum Descriptor {
6768
String,
6869
Externref,
6970
NamedExternref(String),
70-
Enum { name: String, hole: u32 },
71+
Enum {
72+
name: String,
73+
hole: u32,
74+
},
75+
StringEnum {
76+
name: String,
77+
invalid: u32,
78+
hole: u32,
79+
variant_values: Vec<String>,
80+
},
7181
RustStruct(String),
7282
Char,
7383
Option(Box<Descriptor>),
@@ -156,6 +166,19 @@ impl Descriptor {
156166
let hole = get(data);
157167
Descriptor::Enum { name, hole }
158168
}
169+
STRING_ENUM => {
170+
let name = get_string(data);
171+
let variant_count = get(data);
172+
let invalid = variant_count;
173+
let hole = variant_count + 1;
174+
let variant_values = (0..variant_count).map(|_| get_string(data)).collect();
175+
Descriptor::StringEnum {
176+
name,
177+
invalid,
178+
hole,
179+
variant_values,
180+
}
181+
}
159182
RUST_STRUCT => {
160183
let name = get_string(data);
161184
Descriptor::RustStruct(name)

0 commit comments

Comments
 (0)