1
//! WebAssembly example with explicit JavaScript bindings
2
//!
3
//! This example demonstrates how to use JetStream RPC with JavaScript bindings.
4

            
5
#[cfg(target_arch = "wasm32")]
6
use wasm_bindgen::prelude::*;
7

            
8
// WebAssembly bindings
9
#[cfg(target_arch = "wasm32")]
10
#[wasm_bindgen]
11
pub fn encode_message(id: u32, content: String) -> Vec<u8> {
12
    let msg = Message { id, content };
13
    let mut buffer = Vec::new();
14
    msg.encode(&mut buffer).expect("Failed to encode message");
15
    buffer
16
}
17

            
18
#[cfg(target_arch = "wasm32")]
19
#[wasm_bindgen]
20
pub fn decode_message(buffer: &[u8]) -> String {
21
    let mut cursor = Cursor::new(buffer);
22
    match WireFormat::decode::<_, Message>(&mut cursor) {
23
        Ok(msg) => {
24
            format!("{{\"id\":{},\"content\":\"{}\"}}", msg.id, msg.content)
25
        }
26
        Err(_) => "{{\"error\":\"Failed to decode message\"}}".to_string(),
27
    }
28
}
29

            
30
// For native compilation
31
#[cfg(not(target_arch = "wasm32"))]
32
fn main() {
33
    println!("This example is intended for WebAssembly compilation.");
34
    println!("Use the following command to build for WebAssembly:");
35
    println!("cargo build --target wasm32-unknown-unknown --example wasm_example_bindings --release");
36
}
37

            
38
// Required for WebAssembly compilation
39
#[cfg(target_arch = "wasm32")]
40
fn main() {}