A macro to generate constructor to instanicate structs from JsValue using duck-typing.

Overview

ducktor

ducktor is a Rust crate that allows you to create types from wasm_bindgen::JsValue using duck typing.

With ducktor, you can define a struct that specifies the fields and types that you expect from a JsValue, and then use the implement From<JsValue> for it using the #[derive(FromJsValue)] macro. This way, you can use Rust's type system and syntax to work with JavaScript objects in WebAssembly.

Why

  • Using#[wasm_bindgen] on exported types requires the input on an exported function be of the class created by wasm-bindgen which is not always possible
  • Using imported types with #[wasm_bindgen] extern "C" { ... } makes it so that the type is not creatable from Rust. This becomes a problem in shared code where you want to create instance of the type from Rust as well.

Solution

Meet ducktor! A constructor for your structs using duck typing. It allows you to create a struct, as you normally would. Then, you can use the #[derive(FromJsValue)] macro to implement From<JsValue> for your struct. This allows you to use the from method on your struct to create an instance of it from a JsValue.

Internally, it defines and imports a non-existent JavaScript type that matches the struct fields and types. The JsValue is then coerced into this type using JsValue::unchecked_ref and then the struct is created by getting the value of each field from the JS type.

Example

use ducktor::FromJsValue;

// Define a struct that represents a JavaScript object with an a field and a b field
#[derive(FromJsValue)]
struct Data {
    a: u32,
    b: String,
}

// Create a JavaScript object that conforms to the Data struct
fn roundtrip() {
    let data = js_sys::Object::new();
    js_sys::Reflect::set(&data, &"a".into(), &42.into()).unwrap();
    js_sys::Reflect::set(&data, &"b".into(), &"string".into()).unwrap();

    // Convert the JsValue to a Data using the `from_js_value` method
    let data: Data = Data::from(&data.into());
    assert_eq!(data.a, 42);
    assert_eq!(data.b, "string");
}
You might also like...
A collection of unsound rust functions using entirly *safe* code

A collection of unsound rust functions using entirly *safe* code

Realtime audio processing / synthesis using Rust/WASM in the browser.
Realtime audio processing / synthesis using Rust/WASM in the browser.

Rust Audio About This repo is my investigation into using Rust for creative audio coding on various platforms (e.g. desktop, web, etc.), but especiall

call rest api using rust + yew
call rest api using rust + yew

Call Rest API With Rust and Yew: USA Weather Service API Open Data YEW Complete Tutorial YouTube Video https://youtu.be/dSJULWtd3y0 How to run trunk s

Python bindings for akinator-rs using pyo3

Akinator-py python bindings for akinator-rs using pyo3 Installation Prebuilt wheels are uploaded onto pypi, if you platform is supported, you can inst

Low level tooling for WebAssembly in JavaScript using wasm-tools

js-wasm-tools js-wasm-tools compiles some of the API of wasm-tools to JavaScript and WebAssembly via wasm-bindgen. This offers low level tooling for W

Lua bytecode parser written in Rust using nom, part of metaworm's lua decompiler

luac-parser (中文) lua字节码解析器, 目前支持 lua51, lua53, lua54 这是目前效果最好的lua反编译器 metaworm's luadec 的一部分 可以基于此代码定制你所需的lua字节码解析器,编译成WASM,让metaworm's luadec加载使用,来反编

Freeze.rs is a payload toolkit for bypassing EDRs using suspended processes, direct syscalls written in RUST
Freeze.rs is a payload toolkit for bypassing EDRs using suspended processes, direct syscalls written in RUST

Freeze.rs More Information If you want to learn more about the techniques utilized in this framework, please take a look at SourceZero Blog and the or

plugy empowers you to construct agnostic dynamic plugin systems using Rust and WebAssembly.

plugy plugy is a plugin system designed to enable the seamless integration of Rust-based plugins into your application. It provides a runtime environm

RDF playground using WASM-compiled Sophia

SoWasm: an RDF playground based on Sophia This started as an experiment of compiling Sophia into WebAssembly, and grew into a (hopefully) useful playg

Releases(0.1.0)
Owner
Muhammad Hamza
Web Developer - working with latest technologies. In love with Rust and Ferris
Muhammad Hamza
A rust proc-macro which allows for reading and writing to remote objects through a generated enum

Remote-Obj A rust proc-macro which allows for reading and writing fields/variants of (possibly nested) remote objects by generating a single enum whic

Ben Wang 5 Aug 11, 2022
witgen is a library to generate .wit files for WebAssembly in Rust

witgen witgen is a library to help you generate wit definitions in a wit file for WebAssembly. Using this lib in addition to wit-bindgen will help you

Coenen Benjamin 28 Nov 9, 2022
zzhack-cli is a Command Tool to help you quickly generate a WASM WebApp with simple configuration and zero code

English | 中文文档 zzhack-cli is a Command Tool that can help you quickly generate a WASM WebApp with simple configuration and zero code. It's worth menti

null 17 Feb 9, 2023
Easy way to write Node.js module using Rust

node-bindgen Easy way to write native Node.js module using idiomatic Rust Features Easy: Just write idiomatic Rust code, node-bindgen take care of gen

InfinyOn 346 Jan 3, 2023
Safe Rust <---> GraalVM Polyglot bindings using procedural macros

The class macro is the primary way to generate bindings to Java types; it will generate a struct (with generics if specified) that implements Pass and Receive and has all the methods you give stubs for. The methods generated can be used like normal rust methods, however mutability is not enforced. The fully-qualified type name should precede a block containing method and constructor stubs. Java primitives like char, int, and byte are aliased to corresponding Rust types.

Alec Petridis 33 Dec 28, 2022
Lisp but using indentations

Calcit Runner An interpreter for Calcit snapshot file. Home http://calcit-lang.org/ APIs http://apis.calcit-lang.org/ Running Calcit Editor with compa

Calcit 63 Dec 26, 2022
Rust Lambda using Serverless

Rust Serverless Lambda Template

섹스 신청서 4 May 31, 2022
A Web-App written in Rust with Yew, using the same SyntaxHighlighter from Google Code Archive as planetb.ca

PlanetB SyntaxHighlighter About This is a small app, providing static files to have a frontend to format your code so you can paste it with styles to

Christof Weickhardt 2 Dec 14, 2022
Rust-ffi-guide - A guide for doing FFI using Rust

Using unsafe for Fun and Profit A guide to traversing the FFI boundary between Rust and other languages. A rendered version is available here. This gu

Michael Bryan 261 Dec 1, 2022
Parametric surfaces drawn using the Rust + WASM toolchain with WebGL, React, and TypeScript.

Parametric Surfaces in the Browser My.Movie.3.mp4 Wanted to experiment with WebGL using the Rust + WASM toolchain, with React and TypeScript to glue e

Benji Nguyen 45 Oct 21, 2022