1
//! Example of WebAssembly compatibility for JetStream RPC
2
//!
3
//! This example demonstrates how to use JetStream RPC in a WebAssembly context.
4

            
5
use std::io::Cursor;
6

            
7
use jetstream_macros::JetStreamWireFormat;
8
use jetstream_wireformat::WireFormat;
9

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

            
16
// This function would be exported to JavaScript in a real WebAssembly binary
17
fn encode_message(id: u32, content: String) -> Vec<u8> {
18
    let msg = Message { id, content };
19
    let mut buffer = Vec::new();
20
    msg.encode(&mut buffer).expect("Failed to encode message");
21
    buffer
22
}
23

            
24
// This function would be exported to JavaScript in a real WebAssembly binary
25
fn decode_message(buffer: &[u8]) -> (u32, String) {
26
    let mut cursor = Cursor::new(buffer);
27
    let msg: Message =
28
        WireFormat::decode(&mut cursor).expect("Failed to decode message");
29
    (msg.id, msg.content)
30
}
31

            
32
// Simple example function
33
fn main() {
34
    // Create a message
35
    let encoded = encode_message(42, "Hello from WebAssembly!".to_string());
36
    println!("Encoded message: {:?}", encoded);
37

            
38
    // Decode the message
39
    let (id, content) = decode_message(&encoded);
40
    println!("Decoded message: id={}, content=\"{}\"", id, content);
41
}