Skip to content

Commit 03086a8

Browse files
Merge pull request #37 from rikhuijzer/rh/cbor
Add cbor example
2 parents 2b6103e + 9d71570 commit 03086a8

File tree

5 files changed

+110
-1
lines changed

5 files changed

+110
-1
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ See the example for your language:
4040

4141
If you have all the required dependencies, you may build all examples by running `cargo test`.
4242

43+
If you want to pass structured data to Typst, check how it's done with the [rust example using cbor](examples/hello_rust/).
44+
4345
## wasi-stub
4446

4547
The runtime used by typst do not allow the plugin to import any function (beside the ones used by the protocol). In particular, if your plugin is compiled for [WASI](https://wasi.dev/), it will not be able to be loaded by typst.

examples/hello_rust/Cargo.lock

+83-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/hello_rust/Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ edition = "2021"
77
crate-type = ["cdylib"]
88

99
[dependencies]
10+
# Same package and version as Typst uses.
11+
ciborium = "0.2.1"
12+
serde = "1.0"
1013
wasm-minimal-protocol = { path = "../../crates/macro" }
1114

1215

examples/hello_rust/hello.typ

+4
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,8 @@
88
assert.eq(str(p.returns_ok()), "This is an `Ok`")
99
// p.will_panic() // Fails compilation
1010
// p.returns_err() // Fails compilation with an error message
11+
12+
let encoded = cbor.encode((x: 1, y: 2.0))
13+
let decoded = cbor(p.complex_data(encoded))
14+
assert.eq(decoded, 3.0)
1115
}

examples/hello_rust/src/lib.rs

+18
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
use wasm_minimal_protocol::*;
22

3+
// Only necessary when using cbor for passing arguments.
4+
use ciborium::{de::from_reader, ser::into_writer};
5+
36
initiate_protocol!();
47

58
#[wasm_func]
@@ -36,3 +39,18 @@ pub fn returns_err() -> Result<Vec<u8>, String> {
3639
pub fn will_panic() -> Vec<u8> {
3740
panic!("unconditional panic")
3841
}
42+
43+
#[derive(serde::Deserialize)]
44+
struct ComplexDataArgs {
45+
x: i32,
46+
y: f64,
47+
}
48+
49+
#[wasm_func]
50+
pub fn complex_data(arg: &[u8]) -> Vec<u8> {
51+
let args: ComplexDataArgs = from_reader(arg).unwrap();
52+
let sum = args.x as f64 + args.y;
53+
let mut out = Vec::new();
54+
into_writer(&sum, &mut out).unwrap();
55+
out
56+
}

0 commit comments

Comments
 (0)