pub struct ScopedEngine;Expand description
闭包模式引擎
§使用场景
- ✅ 临时脚本执行
- ✅ 需要完全隔离(每次都是新引擎)
- ✅ 偶尔使用(不频繁)
- ✅ 简单API(类似 Py3o)
- ❌ 高频调用(性能较低,请使用 GlobalEngine 或 PooledEngine)
§特点
- 完全隔离:每次都创建新引擎实例
- 简洁API:闭包风格,自动管理生命周期
- 无缓存:无法利用 AST 缓存(每次都是新引擎)
- 线程安全:每个线程独立创建引擎
§示例
use aether::engine::ScopedEngine;
// 基本使用
let result = ScopedEngine::with(|engine| {
engine.eval("Set X 10\n(X + 20)")
}).unwrap();
assert_eq!(result.to_string(), "30");
// 多步骤执行
let result = ScopedEngine::with(|engine| {
engine.eval("Set X 10")?;
engine.eval("Set Y 20")?;
engine.eval("(X + Y)")
}).unwrap();
assert_eq!(result.to_string(), "30");
// 简化版:直接执行单行代码
let result = ScopedEngine::eval("(10 + 20)").unwrap();
assert_eq!(result.to_string(), "30");§与其他模式对比
use aether::engine::{GlobalEngine, EnginePool, ScopedEngine};
// GlobalEngine - 性能最优,但单线程
let result1 = GlobalEngine::eval_isolated("Set X 10\n(X + 20)").unwrap();
// PooledEngine - 多线程,性能好
let pool = EnginePool::new(4);
let result2 = pool.acquire().eval("Set X 10\n(X + 20)").unwrap();
// ScopedEngine - API最简洁,完全隔离
let result3 = ScopedEngine::eval("Set X 10\n(X + 20)").unwrap();
assert_eq!(result1, result2);
assert_eq!(result2, result3);Implementations§
Source§impl ScopedEngine
impl ScopedEngine
Sourcepub fn with<F, T>(f: F) -> Result<T, String>
pub fn with<F, T>(f: F) -> Result<T, String>
使用闭包执行代码(完全隔离)
每次调用都会创建新的引擎实例,执行完毕后自动销毁。
§参数
f: 接收&mut Aether的闭包,返回Result<T, String>
§返回
Ok(T): 闭包的返回值Err(String): 错误信息
§类型参数
F: 闭包类型T: 返回值类型
§示例
use aether::engine::ScopedEngine;
// 单步执行
let result = ScopedEngine::with(|engine| {
engine.eval("(10 + 20)")
}).unwrap();
// 多步执行
let result = ScopedEngine::with(|engine| {
engine.eval("Set X 10")?;
engine.eval("Set Y (X * 2)")?;
engine.eval("(X + Y)")
}).unwrap();
// 自定义返回类型
let (x, y) = ScopedEngine::with(|engine| {
engine.eval("Set X 10")?;
engine.eval("Set Y 20")?;
let x = engine.eval("X")?;
let y = engine.eval("Y")?;
Ok((x, y))
}).unwrap();Sourcepub fn with_all_permissions<F, T>(f: F) -> Result<T, String>
pub fn with_all_permissions<F, T>(f: F) -> Result<T, String>
Sourcepub fn eval(code: &str) -> Result<Value, String>
pub fn eval(code: &str) -> Result<Value, String>
直接执行代码(简化版)
创建新引擎,执行代码,返回结果。 适合简单的单行代码执行。
§参数
code: 要执行的 Aether 代码
§返回
Ok(Value): 执行结果Err(String): 错误信息
§示例
use aether::engine::ScopedEngine;
// 简单表达式
let result = ScopedEngine::eval("(10 + 20)").unwrap();
assert_eq!(result.to_string(), "30");
// 多行代码
let result = ScopedEngine::eval("Set X 10\nSet Y 20\n(X + Y)").unwrap();
assert_eq!(result.to_string(), "30");Auto Trait Implementations§
impl Freeze for ScopedEngine
impl RefUnwindSafe for ScopedEngine
impl Send for ScopedEngine
impl Sync for ScopedEngine
impl Unpin for ScopedEngine
impl UnwindSafe for ScopedEngine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more