forked from bytecodealliance/component-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
46 lines (39 loc) · 1000 Bytes
/
main.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
mod bindings;
use clap::Parser;
use std::fmt;
use bindings::component_book::calculator::{calculate, calculate::Op};
fn parse_operator(op: &str) -> anyhow::Result<Op> {
match op {
"add" => Ok(Op::Add),
_ => anyhow::bail!("Unknown operation: {}", op),
}
}
impl fmt::Display for Op {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Op::Add => write!(f, "+"),
}
}
}
/// A CLI for executing mathematical expressions
/// using WebAssembly
#[derive(Parser)]
#[clap(name = "calculator", version = env!("CARGO_PKG_VERSION"))]
struct Command {
/// The first operand
x: u32,
/// The second operand
y: u32,
/// Expression operator
#[clap(value_parser = parse_operator)]
op: Op,
}
impl Command {
fn run(self) {
let res = calculate::eval_expression(self.op, self.x, self.y);
println!("{} {} {} = {res}", self.x, self.op, self.y);
}
}
fn main() {
Command::parse().run()
}