use simple_json_server::{actor, Actor};
#[derive(Debug, Clone)]
pub struct Calculator {
pub memory: f64,
}
impl Default for Calculator {
fn default() -> Self {
Self { memory: 0.0 }
}
}
#[actor]
impl Calculator {
pub async fn add(&self, a: f64, b: f64) -> f64 {
a + b
}
pub async fn subtract(&self, a: f64, b: f64) -> f64 {
a - b
}
pub async fn multiply(&self, a: f64, b: f64) -> f64 {
a * b
}
pub async fn divide(&self, a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 {
Err("Division by zero".to_string())
} else {
Ok(a / b)
}
}
pub async fn get_memory(&self) -> f64 {
self.memory
}
pub async fn clear_memory(&self) -> String {
"Memory cleared".to_string()
}
pub async fn info(&self) -> String {
"Simple JSON Calculator v1.0".to_string()
}
}
#[tokio::main]
async fn main() {
let calc = Calculator::default();
println!("Calculator Actor Example");
println!("========================");
let add_msg = r#"{"a": 10.5, "b": 5.2}"#;
let result = calc.dispatch("add", add_msg).await;
println!("Add 10.5 + 5.2 = {}", result);
let div_msg = r#"{"a": 20.0, "b": 4.0}"#;
let result = calc.dispatch("divide", div_msg).await;
println!("Divide 20.0 / 4.0 = {}", result);
let div_zero_msg = r#"{"a": 10.0, "b": 0.0}"#;
let result = calc.dispatch("divide", div_zero_msg).await;
println!("Divide 10.0 / 0.0 = {}", result);
let info_msg = r#"{}"#;
let result = calc.dispatch("info", info_msg).await;
println!("Info: {}", result);
let unknown_msg = r#"{}"#;
let result = calc.dispatch("unknown", unknown_msg).await;
println!("Unknown method: {}", result);
}