ergoplatform / ergo-lib-wasm

ergo-lib bindings for JS/TS
Creative Commons Zero v1.0 Universal
4 stars 3 forks source link

Wasm arrays as arguments and return types #4

Closed ross-weir closed 1 year ago

ross-weir commented 1 year ago

Changes

This PR adds the following:

Related wasm-bindgen issues:

The problem with using JSON / serde for handling passing/receiving arrays is that deser/ser converts to JS objects instead of classes so library consumers can't use class methods without converting to or from JSON first. With the derives added in this PR this is no longer needed

Simple example not using arrays but to describe the problem with JSON:

Rust

#[wasm_bindgen]
#[derive(Serialize, Deserialize)]
pub struct MyType(usize);

#[wasm_bindgen]
impl MyType {
    pub fn new(&self, n: usize) -> MyType {
        MyType(n)
    }

    pub fn inner_num(&self) -> usize {
        self.0
    }

    pub fn to_json(&self) -> Result<JsValue, serde_wasm_bindgen::Error> {
        serde_wasm_bindgen::to_value(&self.0)
    }
}

JS

const myType = MyType.new(5);
const myTypeJson = myType.to_json();

myType.inner_num(); // 5
myTypeJson.inner_num(); // doesn't work, json object doesn't have the func

const jsonBackToMyType = MyType.from_json(myTypeJson);
jsonBackToMyType.inner_num(); // 5

The hope is one day wasm_bindgen supports vecs of structs so we can remove this 😄

changeset-bot[bot] commented 1 year ago

⚠️ No Changeset found

Latest commit: 9dbc6deceae3641e8306384be389006ad94d92bc

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR