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
use jetstream_macros::JetStreamWireFormat;
8

            
9
// Define our message type
10
#[derive(Debug, JetStreamWireFormat)]
11
struct Message {
12
    id: u32,
13
    content: String,
14
}
15

            
16
// WebAssembly bindings
17
#[cfg(target_arch = "wasm32")]
18
#[wasm_bindgen]
19
pub fn encode_message(id: u32, content: String) -> Vec<u8> {
20
    let msg = Message { id, content };
21
    let mut buffer = Vec::new();
22
    msg.encode(&mut buffer).expect("Failed to encode message");
23
    buffer
24
}
25

            
26
#[cfg(target_arch = "wasm32")]
27
#[wasm_bindgen]
28
pub fn decode_message(buffer: &[u8]) -> String {
29
    let mut cursor = Cursor::new(buffer);
30
    match WireFormat::decode::<_, Message>(&mut cursor) {
31
        Ok(msg) => format!("{{\"id\":{},\"content\":\"{}\"}}", msg.id, msg.content),
32
        Err(_) => "{{\"error\":\"Failed to decode message\"}}".to_string(),
33
    }
34
}
35

            
36
// For native compilation
37
#[cfg(not(target_arch = "wasm32"))]
38
fn main() {
39
    println!("This example is intended for WebAssembly compilation.");
40
    println!("Use the following command to build for WebAssembly:");
41
    println!("cargo build --target wasm32-unknown-unknown --example wasm_example_bindings --release");
42
}
43

            
44
// Required for WebAssembly compilation
45
#[cfg(target_arch = "wasm32")]
46
fn main() {}