/
agent.rs
55 lines (43 loc) · 1.1 KB
/
agent.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use serde::{Deserialize, Serialize};
use yew_agent::{Agent, AgentLink, HandlerId, Public};
pub struct Worker {
link: AgentLink<Self>,
}
#[derive(Serialize, Deserialize)]
pub struct WorkerInput {
pub n: u32,
}
#[derive(Serialize, Deserialize)]
pub struct WorkerOutput {
pub value: u32,
}
impl Agent for Worker {
type Reach = Public<Self>;
type Message = ();
type Input = WorkerInput;
type Output = WorkerOutput;
fn create(link: AgentLink<Self>) -> Self {
Self { link }
}
fn update(&mut self, _msg: Self::Message) {
// no messaging
}
fn handle_input(&mut self, msg: Self::Input, id: HandlerId) {
// this runs in a web worker
// and does not block the main
// browser thread!
let n = msg.n;
fn fib(n: u32) -> u32 {
if n <= 1 {
1
} else {
fib(n - 1) + fib(n - 2)
}
}
let output = Self::Output { value: fib(n) };
self.link.respond(id, output);
}
fn name_of_resource() -> &'static str {
"wasm.js"
}
}