diff options
| author | sigoden <sigoden@gmail.com> | 2024-04-23 14:32:06 +0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-04-23 14:32:06 +0800 |
| commit | 1cc89eff514669d6459f62cc4eed8e0b34d8ef0c (patch) | |
| tree | ecbee07510fbdbe5f6bf8fdc98dfd25a3a23a5d5 /src/utils | |
| parent | c5506fe39377d864f80175821712b33949241583 (diff) | |
| download | aichat-1cc89eff514669d6459f62cc4eed8e0b34d8ef0c.tar.gz | |
refactor: more async code (#427)
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/mod.rs | 10 | ||||
| -rw-r--r-- | src/utils/spinner.rs | 20 |
2 files changed, 12 insertions, 18 deletions
diff --git a/src/utils/mod.rs b/src/utils/mod.rs index ba438a7..38cf766 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -9,7 +9,7 @@ pub use self::abort_signal::{create_abort_signal, AbortSignal}; pub use self::clipboard::set_text; pub use self::prompt_input::*; pub use self::render_prompt::render_prompt; -pub use self::spinner::{run_spinner, Spinner}; +pub use self::spinner::run_spinner; pub use self::tiktoken::cl100k_base_singleton; use fancy_regex::Regex; @@ -82,14 +82,6 @@ pub fn light_theme_from_colorfgbg(colorfgbg: &str) -> Option<bool> { Some(light) } -pub fn init_tokio_runtime() -> anyhow::Result<tokio::runtime::Runtime> { - use anyhow::Context; - tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .with_context(|| "Failed to init tokio") -} - pub fn sha256sum(input: &str) -> String { let mut hasher = Sha256::new(); hasher.update(input); diff --git a/src/utils/spinner.rs b/src/utils/spinner.rs index 3715eff..0dd4d01 100644 --- a/src/utils/spinner.rs +++ b/src/utils/spinner.rs @@ -2,10 +2,9 @@ use anyhow::Result; use crossterm::{cursor, queue, style, terminal}; use std::{ io::{stdout, Stdout, Write}, - sync::mpsc, - thread, time::Duration, }; +use tokio::{sync::oneshot, time::interval}; pub struct Spinner { index: usize, @@ -56,17 +55,20 @@ impl Spinner { } } -pub fn run_spinner(message: &str, rx: mpsc::Receiver<()>) -> Result<()> { +pub async fn run_spinner(message: &str, rx: oneshot::Receiver<()>) -> Result<()> { let mut writer = stdout(); let mut spinner = Spinner::new(message); - loop { - spinner.step(&mut writer)?; - if let Ok(()) = rx.try_recv() { + let mut interval = interval(Duration::from_millis(50)); + tokio::select! { + _ = async { + loop { + interval.tick().await; + let _ = spinner.step(&mut writer); + } + } => {} + _ = rx => { spinner.stop(&mut writer)?; - break; } - thread::sleep(Duration::from_millis(50)) } - spinner.stop(&mut writer)?; Ok(()) } |
