diff options
| author | delta <darkussdelta@gmail.com> | 2025-10-29 16:35:38 +0100 |
|---|---|---|
| committer | delta <darkussdelta@gmail.com> | 2025-10-29 16:35:38 +0100 |
| commit | d7c66522cf365f516babcfeb1d4a2d36c3ea41af (patch) | |
| tree | 30c7d6103037b31170ae6d8fd58e3849e3cea823 /.config/awesome/quarrel/native/src/lenses/calculator.rs | |
| parent | df418700b7d776f03ee5b58daa2d497cddb45aca (diff) | |
a small refactor
Diffstat (limited to '.config/awesome/quarrel/native/src/lenses/calculator.rs')
| -rw-r--r-- | .config/awesome/quarrel/native/src/lenses/calculator.rs | 89 |
1 files changed, 71 insertions, 18 deletions
diff --git a/.config/awesome/quarrel/native/src/lenses/calculator.rs b/.config/awesome/quarrel/native/src/lenses/calculator.rs index 640bdeb..36f9805 100644 --- a/.config/awesome/quarrel/native/src/lenses/calculator.rs +++ b/.config/awesome/quarrel/native/src/lenses/calculator.rs @@ -1,40 +1,93 @@ -// use meval::eval_str; -use cpc::{ - eval, - units::Unit, +use std::sync::{ + atomic::{ + AtomicBool, + Ordering, + }, + Arc, + LazyLock, + Mutex, +}; + +use fend_core::{ + evaluate_with_interrupt, + Context, + Interrupt, }; use mlua::prelude::*; use crate::lenses::{ - Entry, - Cache, - Lense + Cache, Entries, Entry, Lense }; -pub struct Calculator; +static CTX: LazyLock<Mutex<Context>> = LazyLock::new(|| { + let mut ctx = Context::new(); + ctx.use_coulomb_and_farad(); + Mutex::new(ctx) +}); + +#[derive(Default)] +pub struct Calculator { + should_interrupt: AtomicBool, +} impl Lense for Calculator { const NAME: &str = "Calculator"; - fn get_cache(&self) -> &Cache { - &Cache::Stale + fn init() -> std::sync::Arc<Self> { + Arc::new(Calculator::default()) + } + + #[inline] + fn set_cache(&self, _: Cache) {} + + #[inline] + fn get_cache(&self) -> Cache { + Cache::Stale + } + + #[inline] + fn set_interrupt(&self, interrupt: bool) { + self.should_interrupt.store(interrupt, Ordering::Relaxed); } - fn set_cache(&mut self, _: Cache) {} + #[inline] + fn get_interrupt(&self) -> bool { + self.should_interrupt.load(Ordering::Relaxed) + } - fn query(_: &Lua, input: String) -> Result<Vec<Entry>, anyhow::Error> { - let result = match eval(input.trim(), true, Unit::Celsius, false) { + fn entries(&self, _: &Lua, input: String) -> Result<Entries, anyhow::Error> { + let result = match evaluate_with_interrupt( + input.trim(), + &mut CTX.lock().expect("Failed to acquire Fend context lock"), + self, + ) { Ok(result) => { - format!("{result}") + result.get_main_result().to_string() + } + Err(err) => { + err } - Err(err) => { return Err(anyhow::anyhow!(err)); }, }; - Ok(vec![Entry { + Ok(if result.is_empty() { + Entries::None + } else { + Entries::Single(Entry { message: result, exec: None, - }; 1] - ) + }) + }) + + } + + #[inline] + fn filter(&self, entries: Entries, _: String) -> Entries { + entries } } +impl Interrupt for Calculator { + fn should_interrupt(&self) -> bool { + self.should_interrupt.load(Ordering::Relaxed) + } +} |
