Skip to content

Instantly share code, notes, and snippets.

@asaaki
Last active January 28, 2023 14:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save asaaki/a0d5bb9df59385440e91d8603b84486a to your computer and use it in GitHub Desktop.
Save asaaki/a0d5bb9df59385440e91d8603b84486a to your computer and use it in GitHub Desktop.
Rust-to-JS JSON string exchange (parcel.js, wasm)

Rust, serde-json, wasm, parcel.js

With this combination it is fairly easy to get things done in Rust and utilize it in JavaScript. Yay!

[package]
name = "jane"
version = "0.1.0"
[lib]
crate-type = ["cdylib"]
[dependencies]
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
<html>
<head><title>jane</title></head>
<body>
<script src="./index.js"></script>
<pre id='console'>...</pre>
</body>
</html>
import { memory, get_data, get_data_len } from "./src/lib.rs";
const offset = get_data();
const stringBuffer = new Uint8Array(memory.buffer, offset, get_data_len());
let str = "";
for (let i = 0; i < stringBuffer.length; i++) {
str += String.fromCharCode(stringBuffer[i]);
}
let jane = JSON.parse(str);
console.log("jane:", jane);
let div = document.getElementById('console');
div.innerText = `
(rust string)->(JSON.parse)->(JSON.stringify)
=> ${JSON.stringify(jane)}
`;
// file: src/lib.rs
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
use std::ffi::CString;
use std::os::raw::c_char;
#[no_mangle]
pub fn get_data() -> *mut c_char {
let s = CString::new(jane()).unwrap();
s.into_raw()
}
#[no_mangle]
pub fn get_data_len() -> usize {
jane().len()
}
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8
}
fn jane() -> String {
let jane = Person { name: "Jane".to_string(), age: 35 };
let json = serde_json::to_string(&jane);
json.unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment