use aether::{
Aether,
engine::{EnginePool, GlobalEngine, ScopedEngine},
};
#[tokio::main]
async fn main() {
println!("=== Aether 异步 API 示例 ===\n");
println!("1. 基础 Aether 异步调用:");
basic_async_example().await;
println!("\n2. GlobalEngine 异步调用:");
global_engine_async_example().await;
println!("\n3. EnginePool 异步调用:");
engine_pool_async_example().await;
println!("\n4. ScopedEngine 异步调用:");
scoped_engine_async_example().await;
println!("\n5. 在异步 Web 服务器中使用 (模拟):");
web_server_simulation().await;
println!("\n=== 所有示例完成 ===");
}
async fn basic_async_example() {
let mut engine = Aether::new();
let result = engine
.eval_async(
r#"
Set X 10
Set Y 20
Set Z (X + Y)
Z
"#,
)
.await
.unwrap();
println!(" 结果: {}", result);
}
async fn global_engine_async_example() {
let result = GlobalEngine::eval_isolated_async(
r#"
Set PRICE 100
Set QUANTITY 5
Set TOTAL (PRICE * QUANTITY)
TOTAL
"#,
)
.await
.unwrap();
println!(" 订单总额: {}", result);
GlobalEngine::eval_async("Set COUNTER 0").await.unwrap();
GlobalEngine::eval_async("Set COUNTER (COUNTER + 1)")
.await
.unwrap();
GlobalEngine::eval_async("Set COUNTER (COUNTER + 1)")
.await
.unwrap();
let counter = GlobalEngine::eval_async("COUNTER").await.unwrap();
println!(" 计数器: {}", counter);
GlobalEngine::clear_env();
}
async fn engine_pool_async_example() {
let mut pool = EnginePool::new(4);
for i in 0..3 {
let mut engine = pool.acquire();
let code = format!(
r#"
Set X {}
Set Y (X * 2)
Set RESULT (X + Y)
RESULT
"#,
i * 10
);
let result = engine.eval_async(&code).await.unwrap();
println!(" 任务 {} 结果: {}", i, result);
}
}
async fn scoped_engine_async_example() {
let result = ScopedEngine::eval_async(
r#"
Set NUMBERS [1, 2, 3, 4, 5]
Set SUM 0
For N In NUMBERS {
Set SUM (SUM + N)
}
SUM
"#,
)
.await
.unwrap();
println!(" 数组求和: {}", result);
}
async fn web_server_simulation() {
println!(" 模拟处理 HTTP 请求...");
for req_id in 1..=5 {
handle_request(req_id).await;
}
}
async fn handle_request(req_id: u32) {
let user_id = req_id * 100;
let amount = req_id * 10;
let code = format!(
r#"
Set USER_ID {}
Set AMOUNT {}
Set FEE 5
Set TOTAL (AMOUNT + FEE)
TOTAL
"#,
user_id, amount
);
let result = ScopedEngine::eval_async(&code).await.unwrap();
println!(" 请求 {} (用户 {}): 总金额 = {}", req_id, user_id, result);
}
#[allow(dead_code)]
async fn performance_comparison() {
use std::time::Instant;
let code = r#"
Set X 10
Set Y 20
(X + Y)
"#;
let start = Instant::now();
for _ in 0..1000 {
let mut engine = Aether::new();
engine.eval(code).unwrap();
}
let sync_duration = start.elapsed();
let start = Instant::now();
for _ in 0..1000 {
let mut engine = Aether::new();
engine.eval_async(code).await.unwrap();
}
let async_duration = start.elapsed();
println!("同步版本耗时: {:?}", sync_duration);
println!("异步版本耗时: {:?}", async_duration);
}