With this combination it is fairly easy to get things done in Rust and utilize it in JavaScript. Yay!
Last active
January 28, 2023 14:14
-
-
Save asaaki/a0d5bb9df59385440e91d8603b84486a to your computer and use it in GitHub Desktop.
Rust-to-JS JSON string exchange (parcel.js, wasm)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "jane" | |
version = "0.1.0" | |
[lib] | |
crate-type = ["cdylib"] | |
[dependencies] | |
serde = "1.0" | |
serde_derive = "1.0" | |
serde_json = "1.0" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head><title>jane</title></head> | |
<body> | |
<script src="./index.js"></script> | |
<pre id='console'>...</pre> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)} | |
`; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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