Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON.encode doesn't support Map #54

Closed
fourtf opened this issue Feb 8, 2022 · 1 comment · Fixed by #68
Closed

JSON.encode doesn't support Map #54

fourtf opened this issue Feb 8, 2022 · 1 comment · Fixed by #68
Labels
bug Something isn't working
Milestone

Comments

@fourtf
Copy link

fourtf commented Feb 8, 2022

Rust's HashMap type gets translated to the Map type in typescript. It is possible to use a struct containing a map as a parameter. However the generated glue code incorrectly uses JSON.stringify to convert the parameter into a string. This doesn't work on the Map member as the contained values are ignored. The code thus outputs an empty objects which doesn't contain the values of the Map.

Rust code:

use deno_bindgen::deno_bindgen;
use std::collections::HashMap;

#[deno_bindgen]
struct MyStruct {
    my_map: HashMap<String, String>,
}

#[deno_bindgen]
fn my_fn(my_struct: MyStruct) {
    println!("{:?}", my_struct.my_map);
}

Generated binding for struct:

export type MyStruct = {
  my_map: Map<string, string>
}

Faulty binding using JSON.stringify:

export function my_fn(a0: MyStruct) {
  const a0_buf = encode(JSON.stringify(a0))
  let rawResult = _lib.symbols.my_fn(a0_buf, a0_buf.byteLength)
  const result = rawResult
  return result
}

As such the follow code will not output {a:'b'} but instead {}.

import { my_fn } from "./bindings/bindings.ts";

my_fn({ my_map: new Map([["a", "b"]]) });

This could be mitigated by using Record<T, U> instead of Map<T, U> as it refers to a plain JS-Object which can be properly converted by JSON.stringify.

@fourtf
Copy link
Author

fourtf commented Feb 8, 2022

For the record, I currently simply create a normal JS object and then cast it using {a: 'b'} as unknown as Map<string, string>.

@littledivy littledivy added the bug Something isn't working label Feb 9, 2022
@littledivy littledivy added this to the 0.6.0 milestone Feb 9, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants