Skip to content

Commit c56b1b0

Browse files
committed
webidl: replace From trait with from_js_value method for enums
* Remove From<JSValue> for ENUM * Add `from_js_value` method which returns an Option<ENUM>
1 parent a981dfd commit c56b1b0

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

crates/backend/src/codegen.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ impl ToTokens for ast::ImportEnum {
591591
fn to_tokens(&self, tokens: &mut TokenStream) {
592592
let vis = &self.vis;
593593
let name = &self.name;
594-
let name_string = &self.name.to_string();
594+
let expect_string = format!("attempted to convert invalid JSValue into {}", name);
595595
let variants = &self.variants;
596596
let variant_strings = &self.variant_values;
597597

@@ -625,6 +625,15 @@ impl ToTokens for ast::ImportEnum {
625625
#(#variants = #variant_indexes_ref,)*
626626
}
627627

628+
impl #name {
629+
fn from_js_value(obj: ::wasm_bindgen::JsValue) -> Option<#name> {
630+
obj.as_string().and_then(|obj_str| match obj_str.as_str() {
631+
#(#variant_strings => Some(#variant_paths_ref),)*
632+
_ => None,
633+
})
634+
}
635+
}
636+
628637
impl ::wasm_bindgen::describe::WasmDescribe for #name {
629638
fn describe() {
630639
::wasm_bindgen::JsValue::describe()
@@ -650,21 +659,7 @@ impl ToTokens for ast::ImportEnum {
650659
js: Self::Abi,
651660
extra: &mut ::wasm_bindgen::convert::Stack,
652661
) -> Self {
653-
#name::from(::wasm_bindgen::JsValue::from_abi(js, extra))
654-
}
655-
}
656-
657-
impl From<::wasm_bindgen::JsValue> for #name {
658-
fn from(obj: ::wasm_bindgen::JsValue) -> #name {
659-
let obj_str = match obj.as_string() {
660-
Some(string_value) => string_value,
661-
None => panic!("Can't convert a non-string into {}", #name_string),
662-
};
663-
664-
match obj_str.as_str() {
665-
#(#variant_strings => #variant_paths_ref,)*
666-
unknown_value => panic!("Can't convert \"{}\" into {}", unknown_value, #name_string),
667-
}
662+
#name::from_js_value(::wasm_bindgen::JsValue::from_abi(js, extra)).expect(#expect_string)
668663
}
669664
}
670665

0 commit comments

Comments
 (0)